File: | llvm/lib/Analysis/MemorySSA.cpp |
Warning: | line 2055, column 5 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- MemorySSA.cpp - Memory SSA Builder ---------------------------------===// | ||||
2 | // | ||||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||||
4 | // See https://llvm.org/LICENSE.txt for license information. | ||||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||||
6 | // | ||||
7 | //===----------------------------------------------------------------------===// | ||||
8 | // | ||||
9 | // This file implements the MemorySSA class. | ||||
10 | // | ||||
11 | //===----------------------------------------------------------------------===// | ||||
12 | |||||
13 | #include "llvm/Analysis/MemorySSA.h" | ||||
14 | #include "llvm/ADT/DenseMap.h" | ||||
15 | #include "llvm/ADT/DenseMapInfo.h" | ||||
16 | #include "llvm/ADT/DenseSet.h" | ||||
17 | #include "llvm/ADT/DepthFirstIterator.h" | ||||
18 | #include "llvm/ADT/Hashing.h" | ||||
19 | #include "llvm/ADT/None.h" | ||||
20 | #include "llvm/ADT/Optional.h" | ||||
21 | #include "llvm/ADT/STLExtras.h" | ||||
22 | #include "llvm/ADT/SmallPtrSet.h" | ||||
23 | #include "llvm/ADT/SmallVector.h" | ||||
24 | #include "llvm/ADT/iterator.h" | ||||
25 | #include "llvm/ADT/iterator_range.h" | ||||
26 | #include "llvm/Analysis/AliasAnalysis.h" | ||||
27 | #include "llvm/Analysis/CFGPrinter.h" | ||||
28 | #include "llvm/Analysis/IteratedDominanceFrontier.h" | ||||
29 | #include "llvm/Analysis/MemoryLocation.h" | ||||
30 | #include "llvm/Config/llvm-config.h" | ||||
31 | #include "llvm/IR/AssemblyAnnotationWriter.h" | ||||
32 | #include "llvm/IR/BasicBlock.h" | ||||
33 | #include "llvm/IR/Dominators.h" | ||||
34 | #include "llvm/IR/Function.h" | ||||
35 | #include "llvm/IR/Instruction.h" | ||||
36 | #include "llvm/IR/Instructions.h" | ||||
37 | #include "llvm/IR/IntrinsicInst.h" | ||||
38 | #include "llvm/IR/Intrinsics.h" | ||||
39 | #include "llvm/IR/LLVMContext.h" | ||||
40 | #include "llvm/IR/PassManager.h" | ||||
41 | #include "llvm/IR/Use.h" | ||||
42 | #include "llvm/InitializePasses.h" | ||||
43 | #include "llvm/Pass.h" | ||||
44 | #include "llvm/Support/AtomicOrdering.h" | ||||
45 | #include "llvm/Support/Casting.h" | ||||
46 | #include "llvm/Support/CommandLine.h" | ||||
47 | #include "llvm/Support/Compiler.h" | ||||
48 | #include "llvm/Support/Debug.h" | ||||
49 | #include "llvm/Support/ErrorHandling.h" | ||||
50 | #include "llvm/Support/FormattedStream.h" | ||||
51 | #include "llvm/Support/raw_ostream.h" | ||||
52 | #include <algorithm> | ||||
53 | #include <cassert> | ||||
54 | #include <cstdlib> | ||||
55 | #include <iterator> | ||||
56 | #include <memory> | ||||
57 | #include <utility> | ||||
58 | |||||
59 | using namespace llvm; | ||||
60 | |||||
61 | #define DEBUG_TYPE"memoryssa" "memoryssa" | ||||
62 | |||||
63 | static cl::opt<std::string> | ||||
64 | DotCFGMSSA("dot-cfg-mssa", | ||||
65 | cl::value_desc("file name for generated dot file"), | ||||
66 | cl::desc("file name for generated dot file"), cl::init("")); | ||||
67 | |||||
68 | INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,static void *initializeMemorySSAWrapperPassPassOnce(PassRegistry &Registry) { | ||||
69 | true)static void *initializeMemorySSAWrapperPassPassOnce(PassRegistry &Registry) { | ||||
70 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)initializeDominatorTreeWrapperPassPass(Registry); | ||||
71 | INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)initializeAAResultsWrapperPassPass(Registry); | ||||
72 | INITIALIZE_PASS_END(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,PassInfo *PI = new PassInfo( "Memory SSA", "memoryssa", & MemorySSAWrapperPass::ID, PassInfo::NormalCtor_t(callDefaultCtor <MemorySSAWrapperPass>), false, true); Registry.registerPass (*PI, true); return PI; } static llvm::once_flag InitializeMemorySSAWrapperPassPassFlag ; void llvm::initializeMemorySSAWrapperPassPass(PassRegistry & Registry) { llvm::call_once(InitializeMemorySSAWrapperPassPassFlag , initializeMemorySSAWrapperPassPassOnce, std::ref(Registry)) ; } | ||||
73 | true)PassInfo *PI = new PassInfo( "Memory SSA", "memoryssa", & MemorySSAWrapperPass::ID, PassInfo::NormalCtor_t(callDefaultCtor <MemorySSAWrapperPass>), false, true); Registry.registerPass (*PI, true); return PI; } static llvm::once_flag InitializeMemorySSAWrapperPassPassFlag ; void llvm::initializeMemorySSAWrapperPassPass(PassRegistry & Registry) { llvm::call_once(InitializeMemorySSAWrapperPassPassFlag , initializeMemorySSAWrapperPassPassOnce, std::ref(Registry)) ; } | ||||
74 | |||||
75 | INITIALIZE_PASS_BEGIN(MemorySSAPrinterLegacyPass, "print-memoryssa",static void *initializeMemorySSAPrinterLegacyPassPassOnce(PassRegistry &Registry) { | ||||
76 | "Memory SSA Printer", false, false)static void *initializeMemorySSAPrinterLegacyPassPassOnce(PassRegistry &Registry) { | ||||
77 | INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)initializeMemorySSAWrapperPassPass(Registry); | ||||
78 | INITIALIZE_PASS_END(MemorySSAPrinterLegacyPass, "print-memoryssa",PassInfo *PI = new PassInfo( "Memory SSA Printer", "print-memoryssa" , &MemorySSAPrinterLegacyPass::ID, PassInfo::NormalCtor_t (callDefaultCtor<MemorySSAPrinterLegacyPass>), false, false ); Registry.registerPass(*PI, true); return PI; } static llvm ::once_flag InitializeMemorySSAPrinterLegacyPassPassFlag; void llvm::initializeMemorySSAPrinterLegacyPassPass(PassRegistry & Registry) { llvm::call_once(InitializeMemorySSAPrinterLegacyPassPassFlag , initializeMemorySSAPrinterLegacyPassPassOnce, std::ref(Registry )); } | ||||
79 | "Memory SSA Printer", false, false)PassInfo *PI = new PassInfo( "Memory SSA Printer", "print-memoryssa" , &MemorySSAPrinterLegacyPass::ID, PassInfo::NormalCtor_t (callDefaultCtor<MemorySSAPrinterLegacyPass>), false, false ); Registry.registerPass(*PI, true); return PI; } static llvm ::once_flag InitializeMemorySSAPrinterLegacyPassPassFlag; void llvm::initializeMemorySSAPrinterLegacyPassPass(PassRegistry & Registry) { llvm::call_once(InitializeMemorySSAPrinterLegacyPassPassFlag , initializeMemorySSAPrinterLegacyPassPassOnce, std::ref(Registry )); } | ||||
80 | |||||
81 | static cl::opt<unsigned> MaxCheckLimit( | ||||
82 | "memssa-check-limit", cl::Hidden, cl::init(100), | ||||
83 | cl::desc("The maximum number of stores/phis MemorySSA" | ||||
84 | "will consider trying to walk past (default = 100)")); | ||||
85 | |||||
86 | // Always verify MemorySSA if expensive checking is enabled. | ||||
87 | #ifdef EXPENSIVE_CHECKS | ||||
88 | bool llvm::VerifyMemorySSA = true; | ||||
89 | #else | ||||
90 | bool llvm::VerifyMemorySSA = false; | ||||
91 | #endif | ||||
92 | /// Enables memory ssa as a dependency for loop passes in legacy pass manager. | ||||
93 | cl::opt<bool> llvm::EnableMSSALoopDependency( | ||||
94 | "enable-mssa-loop-dependency", cl::Hidden, cl::init(true), | ||||
95 | cl::desc("Enable MemorySSA dependency for loop pass manager")); | ||||
96 | |||||
97 | static cl::opt<bool, true> | ||||
98 | VerifyMemorySSAX("verify-memoryssa", cl::location(VerifyMemorySSA), | ||||
99 | cl::Hidden, cl::desc("Enable verification of MemorySSA.")); | ||||
100 | |||||
101 | namespace llvm { | ||||
102 | |||||
103 | /// An assembly annotator class to print Memory SSA information in | ||||
104 | /// comments. | ||||
105 | class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter { | ||||
106 | friend class MemorySSA; | ||||
107 | |||||
108 | const MemorySSA *MSSA; | ||||
109 | |||||
110 | public: | ||||
111 | MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {} | ||||
112 | |||||
113 | void emitBasicBlockStartAnnot(const BasicBlock *BB, | ||||
114 | formatted_raw_ostream &OS) override { | ||||
115 | if (MemoryAccess *MA = MSSA->getMemoryAccess(BB)) | ||||
116 | OS << "; " << *MA << "\n"; | ||||
117 | } | ||||
118 | |||||
119 | void emitInstructionAnnot(const Instruction *I, | ||||
120 | formatted_raw_ostream &OS) override { | ||||
121 | if (MemoryAccess *MA = MSSA->getMemoryAccess(I)) | ||||
122 | OS << "; " << *MA << "\n"; | ||||
123 | } | ||||
124 | }; | ||||
125 | |||||
126 | } // end namespace llvm | ||||
127 | |||||
128 | namespace { | ||||
129 | |||||
130 | /// Our current alias analysis API differentiates heavily between calls and | ||||
131 | /// non-calls, and functions called on one usually assert on the other. | ||||
132 | /// This class encapsulates the distinction to simplify other code that wants | ||||
133 | /// "Memory affecting instructions and related data" to use as a key. | ||||
134 | /// For example, this class is used as a densemap key in the use optimizer. | ||||
135 | class MemoryLocOrCall { | ||||
136 | public: | ||||
137 | bool IsCall = false; | ||||
138 | |||||
139 | MemoryLocOrCall(MemoryUseOrDef *MUD) | ||||
140 | : MemoryLocOrCall(MUD->getMemoryInst()) {} | ||||
141 | MemoryLocOrCall(const MemoryUseOrDef *MUD) | ||||
142 | : MemoryLocOrCall(MUD->getMemoryInst()) {} | ||||
143 | |||||
144 | MemoryLocOrCall(Instruction *Inst) { | ||||
145 | if (auto *C = dyn_cast<CallBase>(Inst)) { | ||||
146 | IsCall = true; | ||||
147 | Call = C; | ||||
148 | } else { | ||||
149 | IsCall = false; | ||||
150 | // There is no such thing as a memorylocation for a fence inst, and it is | ||||
151 | // unique in that regard. | ||||
152 | if (!isa<FenceInst>(Inst)) | ||||
153 | Loc = MemoryLocation::get(Inst); | ||||
154 | } | ||||
155 | } | ||||
156 | |||||
157 | explicit MemoryLocOrCall(const MemoryLocation &Loc) : Loc(Loc) {} | ||||
158 | |||||
159 | const CallBase *getCall() const { | ||||
160 | assert(IsCall)((IsCall) ? static_cast<void> (0) : __assert_fail ("IsCall" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 160, __PRETTY_FUNCTION__)); | ||||
161 | return Call; | ||||
162 | } | ||||
163 | |||||
164 | MemoryLocation getLoc() const { | ||||
165 | assert(!IsCall)((!IsCall) ? static_cast<void> (0) : __assert_fail ("!IsCall" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 165, __PRETTY_FUNCTION__)); | ||||
166 | return Loc; | ||||
167 | } | ||||
168 | |||||
169 | bool operator==(const MemoryLocOrCall &Other) const { | ||||
170 | if (IsCall != Other.IsCall) | ||||
171 | return false; | ||||
172 | |||||
173 | if (!IsCall) | ||||
174 | return Loc == Other.Loc; | ||||
175 | |||||
176 | if (Call->getCalledOperand() != Other.Call->getCalledOperand()) | ||||
177 | return false; | ||||
178 | |||||
179 | return Call->arg_size() == Other.Call->arg_size() && | ||||
180 | std::equal(Call->arg_begin(), Call->arg_end(), | ||||
181 | Other.Call->arg_begin()); | ||||
182 | } | ||||
183 | |||||
184 | private: | ||||
185 | union { | ||||
186 | const CallBase *Call; | ||||
187 | MemoryLocation Loc; | ||||
188 | }; | ||||
189 | }; | ||||
190 | |||||
191 | } // end anonymous namespace | ||||
192 | |||||
193 | namespace llvm { | ||||
194 | |||||
195 | template <> struct DenseMapInfo<MemoryLocOrCall> { | ||||
196 | static inline MemoryLocOrCall getEmptyKey() { | ||||
197 | return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getEmptyKey()); | ||||
198 | } | ||||
199 | |||||
200 | static inline MemoryLocOrCall getTombstoneKey() { | ||||
201 | return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getTombstoneKey()); | ||||
202 | } | ||||
203 | |||||
204 | static unsigned getHashValue(const MemoryLocOrCall &MLOC) { | ||||
205 | if (!MLOC.IsCall) | ||||
206 | return hash_combine( | ||||
207 | MLOC.IsCall, | ||||
208 | DenseMapInfo<MemoryLocation>::getHashValue(MLOC.getLoc())); | ||||
209 | |||||
210 | hash_code hash = | ||||
211 | hash_combine(MLOC.IsCall, DenseMapInfo<const Value *>::getHashValue( | ||||
212 | MLOC.getCall()->getCalledOperand())); | ||||
213 | |||||
214 | for (const Value *Arg : MLOC.getCall()->args()) | ||||
215 | hash = hash_combine(hash, DenseMapInfo<const Value *>::getHashValue(Arg)); | ||||
216 | return hash; | ||||
217 | } | ||||
218 | |||||
219 | static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS) { | ||||
220 | return LHS == RHS; | ||||
221 | } | ||||
222 | }; | ||||
223 | |||||
224 | } // end namespace llvm | ||||
225 | |||||
226 | /// This does one-way checks to see if Use could theoretically be hoisted above | ||||
227 | /// MayClobber. This will not check the other way around. | ||||
228 | /// | ||||
229 | /// This assumes that, for the purposes of MemorySSA, Use comes directly after | ||||
230 | /// MayClobber, with no potentially clobbering operations in between them. | ||||
231 | /// (Where potentially clobbering ops are memory barriers, aliased stores, etc.) | ||||
232 | static bool areLoadsReorderable(const LoadInst *Use, | ||||
233 | const LoadInst *MayClobber) { | ||||
234 | bool VolatileUse = Use->isVolatile(); | ||||
235 | bool VolatileClobber = MayClobber->isVolatile(); | ||||
236 | // Volatile operations may never be reordered with other volatile operations. | ||||
237 | if (VolatileUse && VolatileClobber) | ||||
238 | return false; | ||||
239 | // Otherwise, volatile doesn't matter here. From the language reference: | ||||
240 | // 'optimizers may change the order of volatile operations relative to | ||||
241 | // non-volatile operations.'" | ||||
242 | |||||
243 | // If a load is seq_cst, it cannot be moved above other loads. If its ordering | ||||
244 | // is weaker, it can be moved above other loads. We just need to be sure that | ||||
245 | // MayClobber isn't an acquire load, because loads can't be moved above | ||||
246 | // acquire loads. | ||||
247 | // | ||||
248 | // Note that this explicitly *does* allow the free reordering of monotonic (or | ||||
249 | // weaker) loads of the same address. | ||||
250 | bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent; | ||||
251 | bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(), | ||||
252 | AtomicOrdering::Acquire); | ||||
253 | return !(SeqCstUse || MayClobberIsAcquire); | ||||
254 | } | ||||
255 | |||||
256 | namespace { | ||||
257 | |||||
258 | struct ClobberAlias { | ||||
259 | bool IsClobber; | ||||
260 | Optional<AliasResult> AR; | ||||
261 | }; | ||||
262 | |||||
263 | } // end anonymous namespace | ||||
264 | |||||
265 | // Return a pair of {IsClobber (bool), AR (AliasResult)}. It relies on AR being | ||||
266 | // ignored if IsClobber = false. | ||||
267 | template <typename AliasAnalysisType> | ||||
268 | static ClobberAlias | ||||
269 | instructionClobbersQuery(const MemoryDef *MD, const MemoryLocation &UseLoc, | ||||
270 | const Instruction *UseInst, AliasAnalysisType &AA) { | ||||
271 | Instruction *DefInst = MD->getMemoryInst(); | ||||
272 | assert(DefInst && "Defining instruction not actually an instruction")((DefInst && "Defining instruction not actually an instruction" ) ? static_cast<void> (0) : __assert_fail ("DefInst && \"Defining instruction not actually an instruction\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 272, __PRETTY_FUNCTION__)); | ||||
273 | Optional<AliasResult> AR; | ||||
274 | |||||
275 | if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) { | ||||
276 | // These intrinsics will show up as affecting memory, but they are just | ||||
277 | // markers, mostly. | ||||
278 | // | ||||
279 | // FIXME: We probably don't actually want MemorySSA to model these at all | ||||
280 | // (including creating MemoryAccesses for them): we just end up inventing | ||||
281 | // clobbers where they don't really exist at all. Please see D43269 for | ||||
282 | // context. | ||||
283 | switch (II->getIntrinsicID()) { | ||||
284 | case Intrinsic::lifetime_end: | ||||
285 | case Intrinsic::invariant_start: | ||||
286 | case Intrinsic::invariant_end: | ||||
287 | case Intrinsic::assume: | ||||
288 | return {false, NoAlias}; | ||||
289 | case Intrinsic::dbg_addr: | ||||
290 | case Intrinsic::dbg_declare: | ||||
291 | case Intrinsic::dbg_label: | ||||
292 | case Intrinsic::dbg_value: | ||||
293 | llvm_unreachable("debuginfo shouldn't have associated defs!")::llvm::llvm_unreachable_internal("debuginfo shouldn't have associated defs!" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 293); | ||||
294 | default: | ||||
295 | break; | ||||
296 | } | ||||
297 | } | ||||
298 | |||||
299 | if (auto *CB = dyn_cast_or_null<CallBase>(UseInst)) { | ||||
300 | ModRefInfo I = AA.getModRefInfo(DefInst, CB); | ||||
301 | AR = isMustSet(I) ? MustAlias : MayAlias; | ||||
302 | return {isModOrRefSet(I), AR}; | ||||
303 | } | ||||
304 | |||||
305 | if (auto *DefLoad = dyn_cast<LoadInst>(DefInst)) | ||||
306 | if (auto *UseLoad = dyn_cast_or_null<LoadInst>(UseInst)) | ||||
307 | return {!areLoadsReorderable(UseLoad, DefLoad), MayAlias}; | ||||
308 | |||||
309 | ModRefInfo I = AA.getModRefInfo(DefInst, UseLoc); | ||||
310 | AR = isMustSet(I) ? MustAlias : MayAlias; | ||||
311 | return {isModSet(I), AR}; | ||||
312 | } | ||||
313 | |||||
314 | template <typename AliasAnalysisType> | ||||
315 | static ClobberAlias instructionClobbersQuery(MemoryDef *MD, | ||||
316 | const MemoryUseOrDef *MU, | ||||
317 | const MemoryLocOrCall &UseMLOC, | ||||
318 | AliasAnalysisType &AA) { | ||||
319 | // FIXME: This is a temporary hack to allow a single instructionClobbersQuery | ||||
320 | // to exist while MemoryLocOrCall is pushed through places. | ||||
321 | if (UseMLOC.IsCall) | ||||
322 | return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(), | ||||
323 | AA); | ||||
324 | return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(), | ||||
325 | AA); | ||||
326 | } | ||||
327 | |||||
328 | // Return true when MD may alias MU, return false otherwise. | ||||
329 | bool MemorySSAUtil::defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU, | ||||
330 | AliasAnalysis &AA) { | ||||
331 | return instructionClobbersQuery(MD, MU, MemoryLocOrCall(MU), AA).IsClobber; | ||||
332 | } | ||||
333 | |||||
334 | namespace { | ||||
335 | |||||
336 | struct UpwardsMemoryQuery { | ||||
337 | // True if our original query started off as a call | ||||
338 | bool IsCall = false; | ||||
339 | // The pointer location we started the query with. This will be empty if | ||||
340 | // IsCall is true. | ||||
341 | MemoryLocation StartingLoc; | ||||
342 | // This is the instruction we were querying about. | ||||
343 | const Instruction *Inst = nullptr; | ||||
344 | // The MemoryAccess we actually got called with, used to test local domination | ||||
345 | const MemoryAccess *OriginalAccess = nullptr; | ||||
346 | Optional<AliasResult> AR = MayAlias; | ||||
347 | bool SkipSelfAccess = false; | ||||
348 | |||||
349 | UpwardsMemoryQuery() = default; | ||||
350 | |||||
351 | UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access) | ||||
352 | : IsCall(isa<CallBase>(Inst)), Inst(Inst), OriginalAccess(Access) { | ||||
353 | if (!IsCall) | ||||
354 | StartingLoc = MemoryLocation::get(Inst); | ||||
355 | } | ||||
356 | }; | ||||
357 | |||||
358 | } // end anonymous namespace | ||||
359 | |||||
360 | static bool lifetimeEndsAt(MemoryDef *MD, const MemoryLocation &Loc, | ||||
361 | BatchAAResults &AA) { | ||||
362 | Instruction *Inst = MD->getMemoryInst(); | ||||
363 | if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { | ||||
364 | switch (II->getIntrinsicID()) { | ||||
365 | case Intrinsic::lifetime_end: { | ||||
366 | MemoryLocation ArgLoc = MemoryLocation::getAfter(II->getArgOperand(1)); | ||||
367 | return AA.alias(ArgLoc, Loc) == MustAlias; | ||||
368 | } | ||||
369 | default: | ||||
370 | return false; | ||||
371 | } | ||||
372 | } | ||||
373 | return false; | ||||
374 | } | ||||
375 | |||||
376 | template <typename AliasAnalysisType> | ||||
377 | static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysisType &AA, | ||||
378 | const Instruction *I) { | ||||
379 | // If the memory can't be changed, then loads of the memory can't be | ||||
380 | // clobbered. | ||||
381 | if (auto *LI = dyn_cast<LoadInst>(I)) | ||||
382 | return I->hasMetadata(LLVMContext::MD_invariant_load) || | ||||
383 | AA.pointsToConstantMemory(MemoryLocation::get(LI)); | ||||
384 | return false; | ||||
385 | } | ||||
386 | |||||
387 | /// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing | ||||
388 | /// inbetween `Start` and `ClobberAt` can clobbers `Start`. | ||||
389 | /// | ||||
390 | /// This is meant to be as simple and self-contained as possible. Because it | ||||
391 | /// uses no cache, etc., it can be relatively expensive. | ||||
392 | /// | ||||
393 | /// \param Start The MemoryAccess that we want to walk from. | ||||
394 | /// \param ClobberAt A clobber for Start. | ||||
395 | /// \param StartLoc The MemoryLocation for Start. | ||||
396 | /// \param MSSA The MemorySSA instance that Start and ClobberAt belong to. | ||||
397 | /// \param Query The UpwardsMemoryQuery we used for our search. | ||||
398 | /// \param AA The AliasAnalysis we used for our search. | ||||
399 | /// \param AllowImpreciseClobber Always false, unless we do relaxed verify. | ||||
400 | |||||
401 | template <typename AliasAnalysisType> | ||||
402 | LLVM_ATTRIBUTE_UNUSED__attribute__((__unused__)) static void | ||||
403 | checkClobberSanity(const MemoryAccess *Start, MemoryAccess *ClobberAt, | ||||
404 | const MemoryLocation &StartLoc, const MemorySSA &MSSA, | ||||
405 | const UpwardsMemoryQuery &Query, AliasAnalysisType &AA, | ||||
406 | bool AllowImpreciseClobber = false) { | ||||
407 | assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?")((MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?" ) ? static_cast<void> (0) : __assert_fail ("MSSA.dominates(ClobberAt, Start) && \"Clobber doesn't dominate start?\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 407, __PRETTY_FUNCTION__)); | ||||
408 | |||||
409 | if (MSSA.isLiveOnEntryDef(Start)) { | ||||
410 | assert(MSSA.isLiveOnEntryDef(ClobberAt) &&((MSSA.isLiveOnEntryDef(ClobberAt) && "liveOnEntry must clobber itself" ) ? static_cast<void> (0) : __assert_fail ("MSSA.isLiveOnEntryDef(ClobberAt) && \"liveOnEntry must clobber itself\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 411, __PRETTY_FUNCTION__)) | ||||
411 | "liveOnEntry must clobber itself")((MSSA.isLiveOnEntryDef(ClobberAt) && "liveOnEntry must clobber itself" ) ? static_cast<void> (0) : __assert_fail ("MSSA.isLiveOnEntryDef(ClobberAt) && \"liveOnEntry must clobber itself\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 411, __PRETTY_FUNCTION__)); | ||||
412 | return; | ||||
413 | } | ||||
414 | |||||
415 | bool FoundClobber = false; | ||||
416 | DenseSet<ConstMemoryAccessPair> VisitedPhis; | ||||
417 | SmallVector<ConstMemoryAccessPair, 8> Worklist; | ||||
418 | Worklist.emplace_back(Start, StartLoc); | ||||
419 | // Walk all paths from Start to ClobberAt, while looking for clobbers. If one | ||||
420 | // is found, complain. | ||||
421 | while (!Worklist.empty()) { | ||||
422 | auto MAP = Worklist.pop_back_val(); | ||||
423 | // All we care about is that nothing from Start to ClobberAt clobbers Start. | ||||
424 | // We learn nothing from revisiting nodes. | ||||
425 | if (!VisitedPhis.insert(MAP).second) | ||||
426 | continue; | ||||
427 | |||||
428 | for (const auto *MA : def_chain(MAP.first)) { | ||||
429 | if (MA == ClobberAt) { | ||||
430 | if (const auto *MD = dyn_cast<MemoryDef>(MA)) { | ||||
431 | // instructionClobbersQuery isn't essentially free, so don't use `|=`, | ||||
432 | // since it won't let us short-circuit. | ||||
433 | // | ||||
434 | // Also, note that this can't be hoisted out of the `Worklist` loop, | ||||
435 | // since MD may only act as a clobber for 1 of N MemoryLocations. | ||||
436 | FoundClobber = FoundClobber || MSSA.isLiveOnEntryDef(MD); | ||||
437 | if (!FoundClobber) { | ||||
438 | ClobberAlias CA = | ||||
439 | instructionClobbersQuery(MD, MAP.second, Query.Inst, AA); | ||||
440 | if (CA.IsClobber) { | ||||
441 | FoundClobber = true; | ||||
442 | // Not used: CA.AR; | ||||
443 | } | ||||
444 | } | ||||
445 | } | ||||
446 | break; | ||||
447 | } | ||||
448 | |||||
449 | // We should never hit liveOnEntry, unless it's the clobber. | ||||
450 | assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?")((!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?" ) ? static_cast<void> (0) : __assert_fail ("!MSSA.isLiveOnEntryDef(MA) && \"Hit liveOnEntry before clobber?\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 450, __PRETTY_FUNCTION__)); | ||||
451 | |||||
452 | if (const auto *MD = dyn_cast<MemoryDef>(MA)) { | ||||
453 | // If Start is a Def, skip self. | ||||
454 | if (MD == Start) | ||||
455 | continue; | ||||
456 | |||||
457 | assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA)((!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA) . IsClobber && "Found clobber before reaching ClobberAt!" ) ? static_cast<void> (0) : __assert_fail ("!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA) .IsClobber && \"Found clobber before reaching ClobberAt!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 459, __PRETTY_FUNCTION__)) | ||||
458 | .IsClobber &&((!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA) . IsClobber && "Found clobber before reaching ClobberAt!" ) ? static_cast<void> (0) : __assert_fail ("!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA) .IsClobber && \"Found clobber before reaching ClobberAt!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 459, __PRETTY_FUNCTION__)) | ||||
459 | "Found clobber before reaching ClobberAt!")((!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA) . IsClobber && "Found clobber before reaching ClobberAt!" ) ? static_cast<void> (0) : __assert_fail ("!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA) .IsClobber && \"Found clobber before reaching ClobberAt!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 459, __PRETTY_FUNCTION__)); | ||||
460 | continue; | ||||
461 | } | ||||
462 | |||||
463 | if (const auto *MU = dyn_cast<MemoryUse>(MA)) { | ||||
464 | (void)MU; | ||||
465 | assert (MU == Start &&((MU == Start && "Can only find use in def chain if Start is a use" ) ? static_cast<void> (0) : __assert_fail ("MU == Start && \"Can only find use in def chain if Start is a use\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 466, __PRETTY_FUNCTION__)) | ||||
466 | "Can only find use in def chain if Start is a use")((MU == Start && "Can only find use in def chain if Start is a use" ) ? static_cast<void> (0) : __assert_fail ("MU == Start && \"Can only find use in def chain if Start is a use\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 466, __PRETTY_FUNCTION__)); | ||||
467 | continue; | ||||
468 | } | ||||
469 | |||||
470 | assert(isa<MemoryPhi>(MA))((isa<MemoryPhi>(MA)) ? static_cast<void> (0) : __assert_fail ("isa<MemoryPhi>(MA)", "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 470, __PRETTY_FUNCTION__)); | ||||
471 | |||||
472 | // Add reachable phi predecessors | ||||
473 | for (auto ItB = upward_defs_begin( | ||||
474 | {const_cast<MemoryAccess *>(MA), MAP.second}, | ||||
475 | MSSA.getDomTree()), | ||||
476 | ItE = upward_defs_end(); | ||||
477 | ItB != ItE; ++ItB) | ||||
478 | if (MSSA.getDomTree().isReachableFromEntry(ItB.getPhiArgBlock())) | ||||
479 | Worklist.emplace_back(*ItB); | ||||
480 | } | ||||
481 | } | ||||
482 | |||||
483 | // If the verify is done following an optimization, it's possible that | ||||
484 | // ClobberAt was a conservative clobbering, that we can now infer is not a | ||||
485 | // true clobbering access. Don't fail the verify if that's the case. | ||||
486 | // We do have accesses that claim they're optimized, but could be optimized | ||||
487 | // further. Updating all these can be expensive, so allow it for now (FIXME). | ||||
488 | if (AllowImpreciseClobber) | ||||
489 | return; | ||||
490 | |||||
491 | // If ClobberAt is a MemoryPhi, we can assume something above it acted as a | ||||
492 | // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point. | ||||
493 | assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&(((isa<MemoryPhi>(ClobberAt) || FoundClobber) && "ClobberAt never acted as a clobber") ? static_cast<void> (0) : __assert_fail ("(isa<MemoryPhi>(ClobberAt) || FoundClobber) && \"ClobberAt never acted as a clobber\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 494, __PRETTY_FUNCTION__)) | ||||
494 | "ClobberAt never acted as a clobber")(((isa<MemoryPhi>(ClobberAt) || FoundClobber) && "ClobberAt never acted as a clobber") ? static_cast<void> (0) : __assert_fail ("(isa<MemoryPhi>(ClobberAt) || FoundClobber) && \"ClobberAt never acted as a clobber\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 494, __PRETTY_FUNCTION__)); | ||||
495 | } | ||||
496 | |||||
497 | namespace { | ||||
498 | |||||
499 | /// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up | ||||
500 | /// in one class. | ||||
501 | template <class AliasAnalysisType> class ClobberWalker { | ||||
502 | /// Save a few bytes by using unsigned instead of size_t. | ||||
503 | using ListIndex = unsigned; | ||||
504 | |||||
505 | /// Represents a span of contiguous MemoryDefs, potentially ending in a | ||||
506 | /// MemoryPhi. | ||||
507 | struct DefPath { | ||||
508 | MemoryLocation Loc; | ||||
509 | // Note that, because we always walk in reverse, Last will always dominate | ||||
510 | // First. Also note that First and Last are inclusive. | ||||
511 | MemoryAccess *First; | ||||
512 | MemoryAccess *Last; | ||||
513 | Optional<ListIndex> Previous; | ||||
514 | |||||
515 | DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last, | ||||
516 | Optional<ListIndex> Previous) | ||||
517 | : Loc(Loc), First(First), Last(Last), Previous(Previous) {} | ||||
518 | |||||
519 | DefPath(const MemoryLocation &Loc, MemoryAccess *Init, | ||||
520 | Optional<ListIndex> Previous) | ||||
521 | : DefPath(Loc, Init, Init, Previous) {} | ||||
522 | }; | ||||
523 | |||||
524 | const MemorySSA &MSSA; | ||||
525 | AliasAnalysisType &AA; | ||||
526 | DominatorTree &DT; | ||||
527 | UpwardsMemoryQuery *Query; | ||||
528 | unsigned *UpwardWalkLimit; | ||||
529 | |||||
530 | // Phi optimization bookkeeping: | ||||
531 | // List of DefPath to process during the current phi optimization walk. | ||||
532 | SmallVector<DefPath, 32> Paths; | ||||
533 | // List of visited <Access, Location> pairs; we can skip paths already | ||||
534 | // visited with the same memory location. | ||||
535 | DenseSet<ConstMemoryAccessPair> VisitedPhis; | ||||
536 | // Record if phi translation has been performed during the current phi | ||||
537 | // optimization walk, as merging alias results after phi translation can | ||||
538 | // yield incorrect results. Context in PR46156. | ||||
539 | bool PerformedPhiTranslation = false; | ||||
540 | |||||
541 | /// Find the nearest def or phi that `From` can legally be optimized to. | ||||
542 | const MemoryAccess *getWalkTarget(const MemoryPhi *From) const { | ||||
543 | assert(From->getNumOperands() && "Phi with no operands?")((From->getNumOperands() && "Phi with no operands?" ) ? static_cast<void> (0) : __assert_fail ("From->getNumOperands() && \"Phi with no operands?\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 543, __PRETTY_FUNCTION__)); | ||||
544 | |||||
545 | BasicBlock *BB = From->getBlock(); | ||||
546 | MemoryAccess *Result = MSSA.getLiveOnEntryDef(); | ||||
547 | DomTreeNode *Node = DT.getNode(BB); | ||||
548 | while ((Node = Node->getIDom())) { | ||||
549 | auto *Defs = MSSA.getBlockDefs(Node->getBlock()); | ||||
550 | if (Defs) | ||||
551 | return &*Defs->rbegin(); | ||||
552 | } | ||||
553 | return Result; | ||||
554 | } | ||||
555 | |||||
556 | /// Result of calling walkToPhiOrClobber. | ||||
557 | struct UpwardsWalkResult { | ||||
558 | /// The "Result" of the walk. Either a clobber, the last thing we walked, or | ||||
559 | /// both. Include alias info when clobber found. | ||||
560 | MemoryAccess *Result; | ||||
561 | bool IsKnownClobber; | ||||
562 | Optional<AliasResult> AR; | ||||
563 | }; | ||||
564 | |||||
565 | /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last. | ||||
566 | /// This will update Desc.Last as it walks. It will (optionally) also stop at | ||||
567 | /// StopAt. | ||||
568 | /// | ||||
569 | /// This does not test for whether StopAt is a clobber | ||||
570 | UpwardsWalkResult | ||||
571 | walkToPhiOrClobber(DefPath &Desc, const MemoryAccess *StopAt = nullptr, | ||||
572 | const MemoryAccess *SkipStopAt = nullptr) const { | ||||
573 | assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world")((!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world" ) ? static_cast<void> (0) : __assert_fail ("!isa<MemoryUse>(Desc.Last) && \"Uses don't exist in my world\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 573, __PRETTY_FUNCTION__)); | ||||
574 | assert(UpwardWalkLimit && "Need a valid walk limit")((UpwardWalkLimit && "Need a valid walk limit") ? static_cast <void> (0) : __assert_fail ("UpwardWalkLimit && \"Need a valid walk limit\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 574, __PRETTY_FUNCTION__)); | ||||
575 | bool LimitAlreadyReached = false; | ||||
576 | // (*UpwardWalkLimit) may be 0 here, due to the loop in tryOptimizePhi. Set | ||||
577 | // it to 1. This will not do any alias() calls. It either returns in the | ||||
578 | // first iteration in the loop below, or is set back to 0 if all def chains | ||||
579 | // are free of MemoryDefs. | ||||
580 | if (!*UpwardWalkLimit) { | ||||
581 | *UpwardWalkLimit = 1; | ||||
582 | LimitAlreadyReached = true; | ||||
583 | } | ||||
584 | |||||
585 | for (MemoryAccess *Current : def_chain(Desc.Last)) { | ||||
586 | Desc.Last = Current; | ||||
587 | if (Current == StopAt || Current == SkipStopAt) | ||||
588 | return {Current, false, MayAlias}; | ||||
589 | |||||
590 | if (auto *MD = dyn_cast<MemoryDef>(Current)) { | ||||
591 | if (MSSA.isLiveOnEntryDef(MD)) | ||||
592 | return {MD, true, MustAlias}; | ||||
593 | |||||
594 | if (!--*UpwardWalkLimit) | ||||
595 | return {Current, true, MayAlias}; | ||||
596 | |||||
597 | ClobberAlias CA = | ||||
598 | instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA); | ||||
599 | if (CA.IsClobber) | ||||
600 | return {MD, true, CA.AR}; | ||||
601 | } | ||||
602 | } | ||||
603 | |||||
604 | if (LimitAlreadyReached) | ||||
605 | *UpwardWalkLimit = 0; | ||||
606 | |||||
607 | assert(isa<MemoryPhi>(Desc.Last) &&((isa<MemoryPhi>(Desc.Last) && "Ended at a non-clobber that's not a phi?" ) ? static_cast<void> (0) : __assert_fail ("isa<MemoryPhi>(Desc.Last) && \"Ended at a non-clobber that's not a phi?\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 608, __PRETTY_FUNCTION__)) | ||||
608 | "Ended at a non-clobber that's not a phi?")((isa<MemoryPhi>(Desc.Last) && "Ended at a non-clobber that's not a phi?" ) ? static_cast<void> (0) : __assert_fail ("isa<MemoryPhi>(Desc.Last) && \"Ended at a non-clobber that's not a phi?\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 608, __PRETTY_FUNCTION__)); | ||||
609 | return {Desc.Last, false, MayAlias}; | ||||
610 | } | ||||
611 | |||||
612 | void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches, | ||||
613 | ListIndex PriorNode) { | ||||
614 | auto UpwardDefsBegin = upward_defs_begin({Phi, Paths[PriorNode].Loc}, DT, | ||||
615 | &PerformedPhiTranslation); | ||||
616 | auto UpwardDefs = make_range(UpwardDefsBegin, upward_defs_end()); | ||||
617 | for (const MemoryAccessPair &P : UpwardDefs) { | ||||
618 | PausedSearches.push_back(Paths.size()); | ||||
619 | Paths.emplace_back(P.second, P.first, PriorNode); | ||||
620 | } | ||||
621 | } | ||||
622 | |||||
623 | /// Represents a search that terminated after finding a clobber. This clobber | ||||
624 | /// may or may not be present in the path of defs from LastNode..SearchStart, | ||||
625 | /// since it may have been retrieved from cache. | ||||
626 | struct TerminatedPath { | ||||
627 | MemoryAccess *Clobber; | ||||
628 | ListIndex LastNode; | ||||
629 | }; | ||||
630 | |||||
631 | /// Get an access that keeps us from optimizing to the given phi. | ||||
632 | /// | ||||
633 | /// PausedSearches is an array of indices into the Paths array. Its incoming | ||||
634 | /// value is the indices of searches that stopped at the last phi optimization | ||||
635 | /// target. It's left in an unspecified state. | ||||
636 | /// | ||||
637 | /// If this returns None, NewPaused is a vector of searches that terminated | ||||
638 | /// at StopWhere. Otherwise, NewPaused is left in an unspecified state. | ||||
639 | Optional<TerminatedPath> | ||||
640 | getBlockingAccess(const MemoryAccess *StopWhere, | ||||
641 | SmallVectorImpl<ListIndex> &PausedSearches, | ||||
642 | SmallVectorImpl<ListIndex> &NewPaused, | ||||
643 | SmallVectorImpl<TerminatedPath> &Terminated) { | ||||
644 | assert(!PausedSearches.empty() && "No searches to continue?")((!PausedSearches.empty() && "No searches to continue?" ) ? static_cast<void> (0) : __assert_fail ("!PausedSearches.empty() && \"No searches to continue?\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 644, __PRETTY_FUNCTION__)); | ||||
645 | |||||
646 | // BFS vs DFS really doesn't make a difference here, so just do a DFS with | ||||
647 | // PausedSearches as our stack. | ||||
648 | while (!PausedSearches.empty()) { | ||||
649 | ListIndex PathIndex = PausedSearches.pop_back_val(); | ||||
650 | DefPath &Node = Paths[PathIndex]; | ||||
651 | |||||
652 | // If we've already visited this path with this MemoryLocation, we don't | ||||
653 | // need to do so again. | ||||
654 | // | ||||
655 | // NOTE: That we just drop these paths on the ground makes caching | ||||
656 | // behavior sporadic. e.g. given a diamond: | ||||
657 | // A | ||||
658 | // B C | ||||
659 | // D | ||||
660 | // | ||||
661 | // ...If we walk D, B, A, C, we'll only cache the result of phi | ||||
662 | // optimization for A, B, and D; C will be skipped because it dies here. | ||||
663 | // This arguably isn't the worst thing ever, since: | ||||
664 | // - We generally query things in a top-down order, so if we got below D | ||||
665 | // without needing cache entries for {C, MemLoc}, then chances are | ||||
666 | // that those cache entries would end up ultimately unused. | ||||
667 | // - We still cache things for A, so C only needs to walk up a bit. | ||||
668 | // If this behavior becomes problematic, we can fix without a ton of extra | ||||
669 | // work. | ||||
670 | if (!VisitedPhis.insert({Node.Last, Node.Loc}).second) { | ||||
671 | if (PerformedPhiTranslation) { | ||||
672 | // If visiting this path performed Phi translation, don't continue, | ||||
673 | // since it may not be correct to merge results from two paths if one | ||||
674 | // relies on the phi translation. | ||||
675 | TerminatedPath Term{Node.Last, PathIndex}; | ||||
676 | return Term; | ||||
677 | } | ||||
678 | continue; | ||||
679 | } | ||||
680 | |||||
681 | const MemoryAccess *SkipStopWhere = nullptr; | ||||
682 | if (Query->SkipSelfAccess && Node.Loc == Query->StartingLoc) { | ||||
683 | assert(isa<MemoryDef>(Query->OriginalAccess))((isa<MemoryDef>(Query->OriginalAccess)) ? static_cast <void> (0) : __assert_fail ("isa<MemoryDef>(Query->OriginalAccess)" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 683, __PRETTY_FUNCTION__)); | ||||
684 | SkipStopWhere = Query->OriginalAccess; | ||||
685 | } | ||||
686 | |||||
687 | UpwardsWalkResult Res = walkToPhiOrClobber(Node, | ||||
688 | /*StopAt=*/StopWhere, | ||||
689 | /*SkipStopAt=*/SkipStopWhere); | ||||
690 | if (Res.IsKnownClobber) { | ||||
691 | assert(Res.Result != StopWhere && Res.Result != SkipStopWhere)((Res.Result != StopWhere && Res.Result != SkipStopWhere ) ? static_cast<void> (0) : __assert_fail ("Res.Result != StopWhere && Res.Result != SkipStopWhere" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 691, __PRETTY_FUNCTION__)); | ||||
692 | |||||
693 | // If this wasn't a cache hit, we hit a clobber when walking. That's a | ||||
694 | // failure. | ||||
695 | TerminatedPath Term{Res.Result, PathIndex}; | ||||
696 | if (!MSSA.dominates(Res.Result, StopWhere)) | ||||
697 | return Term; | ||||
698 | |||||
699 | // Otherwise, it's a valid thing to potentially optimize to. | ||||
700 | Terminated.push_back(Term); | ||||
701 | continue; | ||||
702 | } | ||||
703 | |||||
704 | if (Res.Result == StopWhere || Res.Result == SkipStopWhere) { | ||||
705 | // We've hit our target. Save this path off for if we want to continue | ||||
706 | // walking. If we are in the mode of skipping the OriginalAccess, and | ||||
707 | // we've reached back to the OriginalAccess, do not save path, we've | ||||
708 | // just looped back to self. | ||||
709 | if (Res.Result != SkipStopWhere) | ||||
710 | NewPaused.push_back(PathIndex); | ||||
711 | continue; | ||||
712 | } | ||||
713 | |||||
714 | assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber")((!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber" ) ? static_cast<void> (0) : __assert_fail ("!MSSA.isLiveOnEntryDef(Res.Result) && \"liveOnEntry is a clobber\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 714, __PRETTY_FUNCTION__)); | ||||
715 | addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex); | ||||
716 | } | ||||
717 | |||||
718 | return None; | ||||
719 | } | ||||
720 | |||||
721 | template <typename T, typename Walker> | ||||
722 | struct generic_def_path_iterator | ||||
723 | : public iterator_facade_base<generic_def_path_iterator<T, Walker>, | ||||
724 | std::forward_iterator_tag, T *> { | ||||
725 | generic_def_path_iterator() {} | ||||
726 | generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {} | ||||
727 | |||||
728 | T &operator*() const { return curNode(); } | ||||
729 | |||||
730 | generic_def_path_iterator &operator++() { | ||||
731 | N = curNode().Previous; | ||||
732 | return *this; | ||||
733 | } | ||||
734 | |||||
735 | bool operator==(const generic_def_path_iterator &O) const { | ||||
736 | if (N.hasValue() != O.N.hasValue()) | ||||
737 | return false; | ||||
738 | return !N.hasValue() || *N == *O.N; | ||||
739 | } | ||||
740 | |||||
741 | private: | ||||
742 | T &curNode() const { return W->Paths[*N]; } | ||||
743 | |||||
744 | Walker *W = nullptr; | ||||
745 | Optional<ListIndex> N = None; | ||||
746 | }; | ||||
747 | |||||
748 | using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>; | ||||
749 | using const_def_path_iterator = | ||||
750 | generic_def_path_iterator<const DefPath, const ClobberWalker>; | ||||
751 | |||||
752 | iterator_range<def_path_iterator> def_path(ListIndex From) { | ||||
753 | return make_range(def_path_iterator(this, From), def_path_iterator()); | ||||
754 | } | ||||
755 | |||||
756 | iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const { | ||||
757 | return make_range(const_def_path_iterator(this, From), | ||||
758 | const_def_path_iterator()); | ||||
759 | } | ||||
760 | |||||
761 | struct OptznResult { | ||||
762 | /// The path that contains our result. | ||||
763 | TerminatedPath PrimaryClobber; | ||||
764 | /// The paths that we can legally cache back from, but that aren't | ||||
765 | /// necessarily the result of the Phi optimization. | ||||
766 | SmallVector<TerminatedPath, 4> OtherClobbers; | ||||
767 | }; | ||||
768 | |||||
769 | ListIndex defPathIndex(const DefPath &N) const { | ||||
770 | // The assert looks nicer if we don't need to do &N | ||||
771 | const DefPath *NP = &N; | ||||
772 | assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&((!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() && "Out of bounds DefPath!" ) ? static_cast<void> (0) : __assert_fail ("!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() && \"Out of bounds DefPath!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 773, __PRETTY_FUNCTION__)) | ||||
773 | "Out of bounds DefPath!")((!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() && "Out of bounds DefPath!" ) ? static_cast<void> (0) : __assert_fail ("!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() && \"Out of bounds DefPath!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 773, __PRETTY_FUNCTION__)); | ||||
774 | return NP - &Paths.front(); | ||||
775 | } | ||||
776 | |||||
777 | /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths | ||||
778 | /// that act as legal clobbers. Note that this won't return *all* clobbers. | ||||
779 | /// | ||||
780 | /// Phi optimization algorithm tl;dr: | ||||
781 | /// - Find the earliest def/phi, A, we can optimize to | ||||
782 | /// - Find if all paths from the starting memory access ultimately reach A | ||||
783 | /// - If not, optimization isn't possible. | ||||
784 | /// - Otherwise, walk from A to another clobber or phi, A'. | ||||
785 | /// - If A' is a def, we're done. | ||||
786 | /// - If A' is a phi, try to optimize it. | ||||
787 | /// | ||||
788 | /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path | ||||
789 | /// terminates when a MemoryAccess that clobbers said MemoryLocation is found. | ||||
790 | OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start, | ||||
791 | const MemoryLocation &Loc) { | ||||
792 | assert(Paths.empty() && VisitedPhis.empty() && !PerformedPhiTranslation &&((Paths.empty() && VisitedPhis.empty() && !PerformedPhiTranslation && "Reset the optimization state.") ? static_cast< void> (0) : __assert_fail ("Paths.empty() && VisitedPhis.empty() && !PerformedPhiTranslation && \"Reset the optimization state.\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 793, __PRETTY_FUNCTION__)) | ||||
793 | "Reset the optimization state.")((Paths.empty() && VisitedPhis.empty() && !PerformedPhiTranslation && "Reset the optimization state.") ? static_cast< void> (0) : __assert_fail ("Paths.empty() && VisitedPhis.empty() && !PerformedPhiTranslation && \"Reset the optimization state.\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 793, __PRETTY_FUNCTION__)); | ||||
794 | |||||
795 | Paths.emplace_back(Loc, Start, Phi, None); | ||||
796 | // Stores how many "valid" optimization nodes we had prior to calling | ||||
797 | // addSearches/getBlockingAccess. Necessary for caching if we had a blocker. | ||||
798 | auto PriorPathsSize = Paths.size(); | ||||
799 | |||||
800 | SmallVector<ListIndex, 16> PausedSearches; | ||||
801 | SmallVector<ListIndex, 8> NewPaused; | ||||
802 | SmallVector<TerminatedPath, 4> TerminatedPaths; | ||||
803 | |||||
804 | addSearches(Phi, PausedSearches, 0); | ||||
805 | |||||
806 | // Moves the TerminatedPath with the "most dominated" Clobber to the end of | ||||
807 | // Paths. | ||||
808 | auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) { | ||||
809 | assert(!Paths.empty() && "Need a path to move")((!Paths.empty() && "Need a path to move") ? static_cast <void> (0) : __assert_fail ("!Paths.empty() && \"Need a path to move\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 809, __PRETTY_FUNCTION__)); | ||||
810 | auto Dom = Paths.begin(); | ||||
811 | for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I) | ||||
812 | if (!MSSA.dominates(I->Clobber, Dom->Clobber)) | ||||
813 | Dom = I; | ||||
814 | auto Last = Paths.end() - 1; | ||||
815 | if (Last != Dom) | ||||
816 | std::iter_swap(Last, Dom); | ||||
817 | }; | ||||
818 | |||||
819 | MemoryPhi *Current = Phi; | ||||
820 | while (true) { | ||||
821 | assert(!MSSA.isLiveOnEntryDef(Current) &&((!MSSA.isLiveOnEntryDef(Current) && "liveOnEntry wasn't treated as a clobber?" ) ? static_cast<void> (0) : __assert_fail ("!MSSA.isLiveOnEntryDef(Current) && \"liveOnEntry wasn't treated as a clobber?\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 822, __PRETTY_FUNCTION__)) | ||||
822 | "liveOnEntry wasn't treated as a clobber?")((!MSSA.isLiveOnEntryDef(Current) && "liveOnEntry wasn't treated as a clobber?" ) ? static_cast<void> (0) : __assert_fail ("!MSSA.isLiveOnEntryDef(Current) && \"liveOnEntry wasn't treated as a clobber?\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 822, __PRETTY_FUNCTION__)); | ||||
823 | |||||
824 | const auto *Target = getWalkTarget(Current); | ||||
825 | // If a TerminatedPath doesn't dominate Target, then it wasn't a legal | ||||
826 | // optimization for the prior phi. | ||||
827 | assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {((all_of(TerminatedPaths, [&](const TerminatedPath &P ) { return MSSA.dominates(P.Clobber, Target); })) ? static_cast <void> (0) : __assert_fail ("all_of(TerminatedPaths, [&](const TerminatedPath &P) { return MSSA.dominates(P.Clobber, Target); })" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 829, __PRETTY_FUNCTION__)) | ||||
828 | return MSSA.dominates(P.Clobber, Target);((all_of(TerminatedPaths, [&](const TerminatedPath &P ) { return MSSA.dominates(P.Clobber, Target); })) ? static_cast <void> (0) : __assert_fail ("all_of(TerminatedPaths, [&](const TerminatedPath &P) { return MSSA.dominates(P.Clobber, Target); })" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 829, __PRETTY_FUNCTION__)) | ||||
829 | }))((all_of(TerminatedPaths, [&](const TerminatedPath &P ) { return MSSA.dominates(P.Clobber, Target); })) ? static_cast <void> (0) : __assert_fail ("all_of(TerminatedPaths, [&](const TerminatedPath &P) { return MSSA.dominates(P.Clobber, Target); })" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 829, __PRETTY_FUNCTION__)); | ||||
830 | |||||
831 | // FIXME: This is broken, because the Blocker may be reported to be | ||||
832 | // liveOnEntry, and we'll happily wait for that to disappear (read: never) | ||||
833 | // For the moment, this is fine, since we do nothing with blocker info. | ||||
834 | if (Optional<TerminatedPath> Blocker = getBlockingAccess( | ||||
835 | Target, PausedSearches, NewPaused, TerminatedPaths)) { | ||||
836 | |||||
837 | // Find the node we started at. We can't search based on N->Last, since | ||||
838 | // we may have gone around a loop with a different MemoryLocation. | ||||
839 | auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) { | ||||
840 | return defPathIndex(N) < PriorPathsSize; | ||||
841 | }); | ||||
842 | assert(Iter != def_path_iterator())((Iter != def_path_iterator()) ? static_cast<void> (0) : __assert_fail ("Iter != def_path_iterator()", "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 842, __PRETTY_FUNCTION__)); | ||||
843 | |||||
844 | DefPath &CurNode = *Iter; | ||||
845 | assert(CurNode.Last == Current)((CurNode.Last == Current) ? static_cast<void> (0) : __assert_fail ("CurNode.Last == Current", "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 845, __PRETTY_FUNCTION__)); | ||||
846 | |||||
847 | // Two things: | ||||
848 | // A. We can't reliably cache all of NewPaused back. Consider a case | ||||
849 | // where we have two paths in NewPaused; one of which can't optimize | ||||
850 | // above this phi, whereas the other can. If we cache the second path | ||||
851 | // back, we'll end up with suboptimal cache entries. We can handle | ||||
852 | // cases like this a bit better when we either try to find all | ||||
853 | // clobbers that block phi optimization, or when our cache starts | ||||
854 | // supporting unfinished searches. | ||||
855 | // B. We can't reliably cache TerminatedPaths back here without doing | ||||
856 | // extra checks; consider a case like: | ||||
857 | // T | ||||
858 | // / \ | ||||
859 | // D C | ||||
860 | // \ / | ||||
861 | // S | ||||
862 | // Where T is our target, C is a node with a clobber on it, D is a | ||||
863 | // diamond (with a clobber *only* on the left or right node, N), and | ||||
864 | // S is our start. Say we walk to D, through the node opposite N | ||||
865 | // (read: ignoring the clobber), and see a cache entry in the top | ||||
866 | // node of D. That cache entry gets put into TerminatedPaths. We then | ||||
867 | // walk up to C (N is later in our worklist), find the clobber, and | ||||
868 | // quit. If we append TerminatedPaths to OtherClobbers, we'll cache | ||||
869 | // the bottom part of D to the cached clobber, ignoring the clobber | ||||
870 | // in N. Again, this problem goes away if we start tracking all | ||||
871 | // blockers for a given phi optimization. | ||||
872 | TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)}; | ||||
873 | return {Result, {}}; | ||||
874 | } | ||||
875 | |||||
876 | // If there's nothing left to search, then all paths led to valid clobbers | ||||
877 | // that we got from our cache; pick the nearest to the start, and allow | ||||
878 | // the rest to be cached back. | ||||
879 | if (NewPaused.empty()) { | ||||
880 | MoveDominatedPathToEnd(TerminatedPaths); | ||||
881 | TerminatedPath Result = TerminatedPaths.pop_back_val(); | ||||
882 | return {Result, std::move(TerminatedPaths)}; | ||||
883 | } | ||||
884 | |||||
885 | MemoryAccess *DefChainEnd = nullptr; | ||||
886 | SmallVector<TerminatedPath, 4> Clobbers; | ||||
887 | for (ListIndex Paused : NewPaused) { | ||||
888 | UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]); | ||||
889 | if (WR.IsKnownClobber) | ||||
890 | Clobbers.push_back({WR.Result, Paused}); | ||||
891 | else | ||||
892 | // Micro-opt: If we hit the end of the chain, save it. | ||||
893 | DefChainEnd = WR.Result; | ||||
894 | } | ||||
895 | |||||
896 | if (!TerminatedPaths.empty()) { | ||||
897 | // If we couldn't find the dominating phi/liveOnEntry in the above loop, | ||||
898 | // do it now. | ||||
899 | if (!DefChainEnd) | ||||
900 | for (auto *MA : def_chain(const_cast<MemoryAccess *>(Target))) | ||||
901 | DefChainEnd = MA; | ||||
902 | assert(DefChainEnd && "Failed to find dominating phi/liveOnEntry")((DefChainEnd && "Failed to find dominating phi/liveOnEntry" ) ? static_cast<void> (0) : __assert_fail ("DefChainEnd && \"Failed to find dominating phi/liveOnEntry\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 902, __PRETTY_FUNCTION__)); | ||||
903 | |||||
904 | // If any of the terminated paths don't dominate the phi we'll try to | ||||
905 | // optimize, we need to figure out what they are and quit. | ||||
906 | const BasicBlock *ChainBB = DefChainEnd->getBlock(); | ||||
907 | for (const TerminatedPath &TP : TerminatedPaths) { | ||||
908 | // Because we know that DefChainEnd is as "high" as we can go, we | ||||
909 | // don't need local dominance checks; BB dominance is sufficient. | ||||
910 | if (DT.dominates(ChainBB, TP.Clobber->getBlock())) | ||||
911 | Clobbers.push_back(TP); | ||||
912 | } | ||||
913 | } | ||||
914 | |||||
915 | // If we have clobbers in the def chain, find the one closest to Current | ||||
916 | // and quit. | ||||
917 | if (!Clobbers.empty()) { | ||||
918 | MoveDominatedPathToEnd(Clobbers); | ||||
919 | TerminatedPath Result = Clobbers.pop_back_val(); | ||||
920 | return {Result, std::move(Clobbers)}; | ||||
921 | } | ||||
922 | |||||
923 | assert(all_of(NewPaused,((all_of(NewPaused, [&](ListIndex I) { return Paths[I].Last == DefChainEnd; })) ? static_cast<void> (0) : __assert_fail ("all_of(NewPaused, [&](ListIndex I) { return Paths[I].Last == DefChainEnd; })" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 924, __PRETTY_FUNCTION__)) | ||||
924 | [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }))((all_of(NewPaused, [&](ListIndex I) { return Paths[I].Last == DefChainEnd; })) ? static_cast<void> (0) : __assert_fail ("all_of(NewPaused, [&](ListIndex I) { return Paths[I].Last == DefChainEnd; })" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 924, __PRETTY_FUNCTION__)); | ||||
925 | |||||
926 | // Because liveOnEntry is a clobber, this must be a phi. | ||||
927 | auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd); | ||||
928 | |||||
929 | PriorPathsSize = Paths.size(); | ||||
930 | PausedSearches.clear(); | ||||
931 | for (ListIndex I : NewPaused) | ||||
932 | addSearches(DefChainPhi, PausedSearches, I); | ||||
933 | NewPaused.clear(); | ||||
934 | |||||
935 | Current = DefChainPhi; | ||||
936 | } | ||||
937 | } | ||||
938 | |||||
939 | void verifyOptResult(const OptznResult &R) const { | ||||
940 | assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {((all_of(R.OtherClobbers, [&](const TerminatedPath &P ) { return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber ); })) ? static_cast<void> (0) : __assert_fail ("all_of(R.OtherClobbers, [&](const TerminatedPath &P) { return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber); })" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 942, __PRETTY_FUNCTION__)) | ||||
941 | return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);((all_of(R.OtherClobbers, [&](const TerminatedPath &P ) { return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber ); })) ? static_cast<void> (0) : __assert_fail ("all_of(R.OtherClobbers, [&](const TerminatedPath &P) { return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber); })" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 942, __PRETTY_FUNCTION__)) | ||||
942 | }))((all_of(R.OtherClobbers, [&](const TerminatedPath &P ) { return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber ); })) ? static_cast<void> (0) : __assert_fail ("all_of(R.OtherClobbers, [&](const TerminatedPath &P) { return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber); })" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 942, __PRETTY_FUNCTION__)); | ||||
943 | } | ||||
944 | |||||
945 | void resetPhiOptznState() { | ||||
946 | Paths.clear(); | ||||
947 | VisitedPhis.clear(); | ||||
948 | PerformedPhiTranslation = false; | ||||
949 | } | ||||
950 | |||||
951 | public: | ||||
952 | ClobberWalker(const MemorySSA &MSSA, AliasAnalysisType &AA, DominatorTree &DT) | ||||
953 | : MSSA(MSSA), AA(AA), DT(DT) {} | ||||
954 | |||||
955 | AliasAnalysisType *getAA() { return &AA; } | ||||
956 | /// Finds the nearest clobber for the given query, optimizing phis if | ||||
957 | /// possible. | ||||
958 | MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q, | ||||
959 | unsigned &UpWalkLimit) { | ||||
960 | Query = &Q; | ||||
961 | UpwardWalkLimit = &UpWalkLimit; | ||||
962 | // Starting limit must be > 0. | ||||
963 | if (!UpWalkLimit) | ||||
964 | UpWalkLimit++; | ||||
965 | |||||
966 | MemoryAccess *Current = Start; | ||||
967 | // This walker pretends uses don't exist. If we're handed one, silently grab | ||||
968 | // its def. (This has the nice side-effect of ensuring we never cache uses) | ||||
969 | if (auto *MU = dyn_cast<MemoryUse>(Start)) | ||||
970 | Current = MU->getDefiningAccess(); | ||||
971 | |||||
972 | DefPath FirstDesc(Q.StartingLoc, Current, Current, None); | ||||
973 | // Fast path for the overly-common case (no crazy phi optimization | ||||
974 | // necessary) | ||||
975 | UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc); | ||||
976 | MemoryAccess *Result; | ||||
977 | if (WalkResult.IsKnownClobber) { | ||||
978 | Result = WalkResult.Result; | ||||
979 | Q.AR = WalkResult.AR; | ||||
980 | } else { | ||||
981 | OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last), | ||||
982 | Current, Q.StartingLoc); | ||||
983 | verifyOptResult(OptRes); | ||||
984 | resetPhiOptznState(); | ||||
985 | Result = OptRes.PrimaryClobber.Clobber; | ||||
986 | } | ||||
987 | |||||
988 | #ifdef EXPENSIVE_CHECKS | ||||
989 | if (!Q.SkipSelfAccess && *UpwardWalkLimit > 0) | ||||
990 | checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA); | ||||
991 | #endif | ||||
992 | return Result; | ||||
993 | } | ||||
994 | }; | ||||
995 | |||||
996 | struct RenamePassData { | ||||
997 | DomTreeNode *DTN; | ||||
998 | DomTreeNode::const_iterator ChildIt; | ||||
999 | MemoryAccess *IncomingVal; | ||||
1000 | |||||
1001 | RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It, | ||||
1002 | MemoryAccess *M) | ||||
1003 | : DTN(D), ChildIt(It), IncomingVal(M) {} | ||||
1004 | |||||
1005 | void swap(RenamePassData &RHS) { | ||||
1006 | std::swap(DTN, RHS.DTN); | ||||
1007 | std::swap(ChildIt, RHS.ChildIt); | ||||
1008 | std::swap(IncomingVal, RHS.IncomingVal); | ||||
1009 | } | ||||
1010 | }; | ||||
1011 | |||||
1012 | } // end anonymous namespace | ||||
1013 | |||||
1014 | namespace llvm { | ||||
1015 | |||||
1016 | template <class AliasAnalysisType> class MemorySSA::ClobberWalkerBase { | ||||
1017 | ClobberWalker<AliasAnalysisType> Walker; | ||||
1018 | MemorySSA *MSSA; | ||||
1019 | |||||
1020 | public: | ||||
1021 | ClobberWalkerBase(MemorySSA *M, AliasAnalysisType *A, DominatorTree *D) | ||||
1022 | : Walker(*M, *A, *D), MSSA(M) {} | ||||
1023 | |||||
1024 | MemoryAccess *getClobberingMemoryAccessBase(MemoryAccess *, | ||||
1025 | const MemoryLocation &, | ||||
1026 | unsigned &); | ||||
1027 | // Third argument (bool), defines whether the clobber search should skip the | ||||
1028 | // original queried access. If true, there will be a follow-up query searching | ||||
1029 | // for a clobber access past "self". Note that the Optimized access is not | ||||
1030 | // updated if a new clobber is found by this SkipSelf search. If this | ||||
1031 | // additional query becomes heavily used we may decide to cache the result. | ||||
1032 | // Walker instantiations will decide how to set the SkipSelf bool. | ||||
1033 | MemoryAccess *getClobberingMemoryAccessBase(MemoryAccess *, unsigned &, bool); | ||||
1034 | }; | ||||
1035 | |||||
1036 | /// A MemorySSAWalker that does AA walks to disambiguate accesses. It no | ||||
1037 | /// longer does caching on its own, but the name has been retained for the | ||||
1038 | /// moment. | ||||
1039 | template <class AliasAnalysisType> | ||||
1040 | class MemorySSA::CachingWalker final : public MemorySSAWalker { | ||||
1041 | ClobberWalkerBase<AliasAnalysisType> *Walker; | ||||
1042 | |||||
1043 | public: | ||||
1044 | CachingWalker(MemorySSA *M, ClobberWalkerBase<AliasAnalysisType> *W) | ||||
1045 | : MemorySSAWalker(M), Walker(W) {} | ||||
1046 | ~CachingWalker() override = default; | ||||
1047 | |||||
1048 | using MemorySSAWalker::getClobberingMemoryAccess; | ||||
1049 | |||||
1050 | MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, unsigned &UWL) { | ||||
1051 | return Walker->getClobberingMemoryAccessBase(MA, UWL, false); | ||||
1052 | } | ||||
1053 | MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, | ||||
1054 | const MemoryLocation &Loc, | ||||
1055 | unsigned &UWL) { | ||||
1056 | return Walker->getClobberingMemoryAccessBase(MA, Loc, UWL); | ||||
1057 | } | ||||
1058 | |||||
1059 | MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA) override { | ||||
1060 | unsigned UpwardWalkLimit = MaxCheckLimit; | ||||
1061 | return getClobberingMemoryAccess(MA, UpwardWalkLimit); | ||||
1062 | } | ||||
1063 | MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, | ||||
1064 | const MemoryLocation &Loc) override { | ||||
1065 | unsigned UpwardWalkLimit = MaxCheckLimit; | ||||
1066 | return getClobberingMemoryAccess(MA, Loc, UpwardWalkLimit); | ||||
1067 | } | ||||
1068 | |||||
1069 | void invalidateInfo(MemoryAccess *MA) override { | ||||
1070 | if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) | ||||
1071 | MUD->resetOptimized(); | ||||
1072 | } | ||||
1073 | }; | ||||
1074 | |||||
1075 | template <class AliasAnalysisType> | ||||
1076 | class MemorySSA::SkipSelfWalker final : public MemorySSAWalker { | ||||
1077 | ClobberWalkerBase<AliasAnalysisType> *Walker; | ||||
1078 | |||||
1079 | public: | ||||
1080 | SkipSelfWalker(MemorySSA *M, ClobberWalkerBase<AliasAnalysisType> *W) | ||||
1081 | : MemorySSAWalker(M), Walker(W) {} | ||||
1082 | ~SkipSelfWalker() override = default; | ||||
1083 | |||||
1084 | using MemorySSAWalker::getClobberingMemoryAccess; | ||||
1085 | |||||
1086 | MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, unsigned &UWL) { | ||||
1087 | return Walker->getClobberingMemoryAccessBase(MA, UWL, true); | ||||
1088 | } | ||||
1089 | MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, | ||||
1090 | const MemoryLocation &Loc, | ||||
1091 | unsigned &UWL) { | ||||
1092 | return Walker->getClobberingMemoryAccessBase(MA, Loc, UWL); | ||||
1093 | } | ||||
1094 | |||||
1095 | MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA) override { | ||||
1096 | unsigned UpwardWalkLimit = MaxCheckLimit; | ||||
1097 | return getClobberingMemoryAccess(MA, UpwardWalkLimit); | ||||
1098 | } | ||||
1099 | MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, | ||||
1100 | const MemoryLocation &Loc) override { | ||||
1101 | unsigned UpwardWalkLimit = MaxCheckLimit; | ||||
1102 | return getClobberingMemoryAccess(MA, Loc, UpwardWalkLimit); | ||||
1103 | } | ||||
1104 | |||||
1105 | void invalidateInfo(MemoryAccess *MA) override { | ||||
1106 | if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) | ||||
1107 | MUD->resetOptimized(); | ||||
1108 | } | ||||
1109 | }; | ||||
1110 | |||||
1111 | } // end namespace llvm | ||||
1112 | |||||
1113 | void MemorySSA::renameSuccessorPhis(BasicBlock *BB, MemoryAccess *IncomingVal, | ||||
1114 | bool RenameAllUses) { | ||||
1115 | // Pass through values to our successors | ||||
1116 | for (const BasicBlock *S : successors(BB)) { | ||||
1117 | auto It = PerBlockAccesses.find(S); | ||||
1118 | // Rename the phi nodes in our successor block | ||||
1119 | if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front())) | ||||
1120 | continue; | ||||
1121 | AccessList *Accesses = It->second.get(); | ||||
1122 | auto *Phi = cast<MemoryPhi>(&Accesses->front()); | ||||
1123 | if (RenameAllUses) { | ||||
1124 | bool ReplacementDone = false; | ||||
1125 | for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) | ||||
1126 | if (Phi->getIncomingBlock(I) == BB) { | ||||
1127 | Phi->setIncomingValue(I, IncomingVal); | ||||
1128 | ReplacementDone = true; | ||||
1129 | } | ||||
1130 | (void) ReplacementDone; | ||||
1131 | assert(ReplacementDone && "Incomplete phi during partial rename")((ReplacementDone && "Incomplete phi during partial rename" ) ? static_cast<void> (0) : __assert_fail ("ReplacementDone && \"Incomplete phi during partial rename\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1131, __PRETTY_FUNCTION__)); | ||||
1132 | } else | ||||
1133 | Phi->addIncoming(IncomingVal, BB); | ||||
1134 | } | ||||
1135 | } | ||||
1136 | |||||
1137 | /// Rename a single basic block into MemorySSA form. | ||||
1138 | /// Uses the standard SSA renaming algorithm. | ||||
1139 | /// \returns The new incoming value. | ||||
1140 | MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB, MemoryAccess *IncomingVal, | ||||
1141 | bool RenameAllUses) { | ||||
1142 | auto It = PerBlockAccesses.find(BB); | ||||
1143 | // Skip most processing if the list is empty. | ||||
1144 | if (It != PerBlockAccesses.end()) { | ||||
1145 | AccessList *Accesses = It->second.get(); | ||||
1146 | for (MemoryAccess &L : *Accesses) { | ||||
1147 | if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) { | ||||
1148 | if (MUD->getDefiningAccess() == nullptr || RenameAllUses) | ||||
1149 | MUD->setDefiningAccess(IncomingVal); | ||||
1150 | if (isa<MemoryDef>(&L)) | ||||
1151 | IncomingVal = &L; | ||||
1152 | } else { | ||||
1153 | IncomingVal = &L; | ||||
1154 | } | ||||
1155 | } | ||||
1156 | } | ||||
1157 | return IncomingVal; | ||||
1158 | } | ||||
1159 | |||||
1160 | /// This is the standard SSA renaming algorithm. | ||||
1161 | /// | ||||
1162 | /// We walk the dominator tree in preorder, renaming accesses, and then filling | ||||
1163 | /// in phi nodes in our successors. | ||||
1164 | void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal, | ||||
1165 | SmallPtrSetImpl<BasicBlock *> &Visited, | ||||
1166 | bool SkipVisited, bool RenameAllUses) { | ||||
1167 | assert(Root && "Trying to rename accesses in an unreachable block")((Root && "Trying to rename accesses in an unreachable block" ) ? static_cast<void> (0) : __assert_fail ("Root && \"Trying to rename accesses in an unreachable block\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1167, __PRETTY_FUNCTION__)); | ||||
1168 | |||||
1169 | SmallVector<RenamePassData, 32> WorkStack; | ||||
1170 | // Skip everything if we already renamed this block and we are skipping. | ||||
1171 | // Note: You can't sink this into the if, because we need it to occur | ||||
1172 | // regardless of whether we skip blocks or not. | ||||
1173 | bool AlreadyVisited = !Visited.insert(Root->getBlock()).second; | ||||
1174 | if (SkipVisited && AlreadyVisited) | ||||
1175 | return; | ||||
1176 | |||||
1177 | IncomingVal = renameBlock(Root->getBlock(), IncomingVal, RenameAllUses); | ||||
1178 | renameSuccessorPhis(Root->getBlock(), IncomingVal, RenameAllUses); | ||||
1179 | WorkStack.push_back({Root, Root->begin(), IncomingVal}); | ||||
1180 | |||||
1181 | while (!WorkStack.empty()) { | ||||
1182 | DomTreeNode *Node = WorkStack.back().DTN; | ||||
1183 | DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt; | ||||
1184 | IncomingVal = WorkStack.back().IncomingVal; | ||||
1185 | |||||
1186 | if (ChildIt == Node->end()) { | ||||
1187 | WorkStack.pop_back(); | ||||
1188 | } else { | ||||
1189 | DomTreeNode *Child = *ChildIt; | ||||
1190 | ++WorkStack.back().ChildIt; | ||||
1191 | BasicBlock *BB = Child->getBlock(); | ||||
1192 | // Note: You can't sink this into the if, because we need it to occur | ||||
1193 | // regardless of whether we skip blocks or not. | ||||
1194 | AlreadyVisited = !Visited.insert(BB).second; | ||||
1195 | if (SkipVisited && AlreadyVisited) { | ||||
1196 | // We already visited this during our renaming, which can happen when | ||||
1197 | // being asked to rename multiple blocks. Figure out the incoming val, | ||||
1198 | // which is the last def. | ||||
1199 | // Incoming value can only change if there is a block def, and in that | ||||
1200 | // case, it's the last block def in the list. | ||||
1201 | if (auto *BlockDefs = getWritableBlockDefs(BB)) | ||||
1202 | IncomingVal = &*BlockDefs->rbegin(); | ||||
1203 | } else | ||||
1204 | IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses); | ||||
1205 | renameSuccessorPhis(BB, IncomingVal, RenameAllUses); | ||||
1206 | WorkStack.push_back({Child, Child->begin(), IncomingVal}); | ||||
1207 | } | ||||
1208 | } | ||||
1209 | } | ||||
1210 | |||||
1211 | /// This handles unreachable block accesses by deleting phi nodes in | ||||
1212 | /// unreachable blocks, and marking all other unreachable MemoryAccess's as | ||||
1213 | /// being uses of the live on entry definition. | ||||
1214 | void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) { | ||||
1215 | assert(!DT->isReachableFromEntry(BB) &&((!DT->isReachableFromEntry(BB) && "Reachable block found while handling unreachable blocks" ) ? static_cast<void> (0) : __assert_fail ("!DT->isReachableFromEntry(BB) && \"Reachable block found while handling unreachable blocks\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1216, __PRETTY_FUNCTION__)) | ||||
1216 | "Reachable block found while handling unreachable blocks")((!DT->isReachableFromEntry(BB) && "Reachable block found while handling unreachable blocks" ) ? static_cast<void> (0) : __assert_fail ("!DT->isReachableFromEntry(BB) && \"Reachable block found while handling unreachable blocks\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1216, __PRETTY_FUNCTION__)); | ||||
1217 | |||||
1218 | // Make sure phi nodes in our reachable successors end up with a | ||||
1219 | // LiveOnEntryDef for our incoming edge, even though our block is forward | ||||
1220 | // unreachable. We could just disconnect these blocks from the CFG fully, | ||||
1221 | // but we do not right now. | ||||
1222 | for (const BasicBlock *S : successors(BB)) { | ||||
1223 | if (!DT->isReachableFromEntry(S)) | ||||
1224 | continue; | ||||
1225 | auto It = PerBlockAccesses.find(S); | ||||
1226 | // Rename the phi nodes in our successor block | ||||
1227 | if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front())) | ||||
1228 | continue; | ||||
1229 | AccessList *Accesses = It->second.get(); | ||||
1230 | auto *Phi = cast<MemoryPhi>(&Accesses->front()); | ||||
1231 | Phi->addIncoming(LiveOnEntryDef.get(), BB); | ||||
1232 | } | ||||
1233 | |||||
1234 | auto It = PerBlockAccesses.find(BB); | ||||
1235 | if (It == PerBlockAccesses.end()) | ||||
1236 | return; | ||||
1237 | |||||
1238 | auto &Accesses = It->second; | ||||
1239 | for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) { | ||||
1240 | auto Next = std::next(AI); | ||||
1241 | // If we have a phi, just remove it. We are going to replace all | ||||
1242 | // users with live on entry. | ||||
1243 | if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI)) | ||||
1244 | UseOrDef->setDefiningAccess(LiveOnEntryDef.get()); | ||||
1245 | else | ||||
1246 | Accesses->erase(AI); | ||||
1247 | AI = Next; | ||||
1248 | } | ||||
1249 | } | ||||
1250 | |||||
1251 | MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT) | ||||
1252 | : AA(nullptr), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr), | ||||
1253 | SkipWalker(nullptr), NextID(0) { | ||||
1254 | // Build MemorySSA using a batch alias analysis. This reuses the internal | ||||
1255 | // state that AA collects during an alias()/getModRefInfo() call. This is | ||||
1256 | // safe because there are no CFG changes while building MemorySSA and can | ||||
1257 | // significantly reduce the time spent by the compiler in AA, because we will | ||||
1258 | // make queries about all the instructions in the Function. | ||||
1259 | assert(AA && "No alias analysis?")((AA && "No alias analysis?") ? static_cast<void> (0) : __assert_fail ("AA && \"No alias analysis?\"", "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1259, __PRETTY_FUNCTION__)); | ||||
1260 | BatchAAResults BatchAA(*AA); | ||||
1261 | buildMemorySSA(BatchAA); | ||||
1262 | // Intentionally leave AA to nullptr while building so we don't accidently | ||||
1263 | // use non-batch AliasAnalysis. | ||||
1264 | this->AA = AA; | ||||
1265 | // Also create the walker here. | ||||
1266 | getWalker(); | ||||
1267 | } | ||||
1268 | |||||
1269 | MemorySSA::~MemorySSA() { | ||||
1270 | // Drop all our references | ||||
1271 | for (const auto &Pair : PerBlockAccesses) | ||||
1272 | for (MemoryAccess &MA : *Pair.second) | ||||
1273 | MA.dropAllReferences(); | ||||
1274 | } | ||||
1275 | |||||
1276 | MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) { | ||||
1277 | auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr)); | ||||
1278 | |||||
1279 | if (Res.second) | ||||
1280 | Res.first->second = std::make_unique<AccessList>(); | ||||
1281 | return Res.first->second.get(); | ||||
1282 | } | ||||
1283 | |||||
1284 | MemorySSA::DefsList *MemorySSA::getOrCreateDefsList(const BasicBlock *BB) { | ||||
1285 | auto Res = PerBlockDefs.insert(std::make_pair(BB, nullptr)); | ||||
1286 | |||||
1287 | if (Res.second) | ||||
1288 | Res.first->second = std::make_unique<DefsList>(); | ||||
1289 | return Res.first->second.get(); | ||||
1290 | } | ||||
1291 | |||||
1292 | namespace llvm { | ||||
1293 | |||||
1294 | /// This class is a batch walker of all MemoryUse's in the program, and points | ||||
1295 | /// their defining access at the thing that actually clobbers them. Because it | ||||
1296 | /// is a batch walker that touches everything, it does not operate like the | ||||
1297 | /// other walkers. This walker is basically performing a top-down SSA renaming | ||||
1298 | /// pass, where the version stack is used as the cache. This enables it to be | ||||
1299 | /// significantly more time and memory efficient than using the regular walker, | ||||
1300 | /// which is walking bottom-up. | ||||
1301 | class MemorySSA::OptimizeUses { | ||||
1302 | public: | ||||
1303 | OptimizeUses(MemorySSA *MSSA, CachingWalker<BatchAAResults> *Walker, | ||||
1304 | BatchAAResults *BAA, DominatorTree *DT) | ||||
1305 | : MSSA(MSSA), Walker(Walker), AA(BAA), DT(DT) {} | ||||
1306 | |||||
1307 | void optimizeUses(); | ||||
1308 | |||||
1309 | private: | ||||
1310 | /// This represents where a given memorylocation is in the stack. | ||||
1311 | struct MemlocStackInfo { | ||||
1312 | // This essentially is keeping track of versions of the stack. Whenever | ||||
1313 | // the stack changes due to pushes or pops, these versions increase. | ||||
1314 | unsigned long StackEpoch; | ||||
1315 | unsigned long PopEpoch; | ||||
1316 | // This is the lower bound of places on the stack to check. It is equal to | ||||
1317 | // the place the last stack walk ended. | ||||
1318 | // Note: Correctness depends on this being initialized to 0, which densemap | ||||
1319 | // does | ||||
1320 | unsigned long LowerBound; | ||||
1321 | const BasicBlock *LowerBoundBlock; | ||||
1322 | // This is where the last walk for this memory location ended. | ||||
1323 | unsigned long LastKill; | ||||
1324 | bool LastKillValid; | ||||
1325 | Optional<AliasResult> AR; | ||||
1326 | }; | ||||
1327 | |||||
1328 | void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &, | ||||
1329 | SmallVectorImpl<MemoryAccess *> &, | ||||
1330 | DenseMap<MemoryLocOrCall, MemlocStackInfo> &); | ||||
1331 | |||||
1332 | MemorySSA *MSSA; | ||||
1333 | CachingWalker<BatchAAResults> *Walker; | ||||
1334 | BatchAAResults *AA; | ||||
1335 | DominatorTree *DT; | ||||
1336 | }; | ||||
1337 | |||||
1338 | } // end namespace llvm | ||||
1339 | |||||
1340 | /// Optimize the uses in a given block This is basically the SSA renaming | ||||
1341 | /// algorithm, with one caveat: We are able to use a single stack for all | ||||
1342 | /// MemoryUses. This is because the set of *possible* reaching MemoryDefs is | ||||
1343 | /// the same for every MemoryUse. The *actual* clobbering MemoryDef is just | ||||
1344 | /// going to be some position in that stack of possible ones. | ||||
1345 | /// | ||||
1346 | /// We track the stack positions that each MemoryLocation needs | ||||
1347 | /// to check, and last ended at. This is because we only want to check the | ||||
1348 | /// things that changed since last time. The same MemoryLocation should | ||||
1349 | /// get clobbered by the same store (getModRefInfo does not use invariantness or | ||||
1350 | /// things like this, and if they start, we can modify MemoryLocOrCall to | ||||
1351 | /// include relevant data) | ||||
1352 | void MemorySSA::OptimizeUses::optimizeUsesInBlock( | ||||
1353 | const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch, | ||||
1354 | SmallVectorImpl<MemoryAccess *> &VersionStack, | ||||
1355 | DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) { | ||||
1356 | |||||
1357 | /// If no accesses, nothing to do. | ||||
1358 | MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB); | ||||
1359 | if (Accesses == nullptr) | ||||
1360 | return; | ||||
1361 | |||||
1362 | // Pop everything that doesn't dominate the current block off the stack, | ||||
1363 | // increment the PopEpoch to account for this. | ||||
1364 | while (true) { | ||||
1365 | assert(((!VersionStack.empty() && "Version stack should have liveOnEntry sentinel dominating everything" ) ? static_cast<void> (0) : __assert_fail ("!VersionStack.empty() && \"Version stack should have liveOnEntry sentinel dominating everything\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1367, __PRETTY_FUNCTION__)) | ||||
1366 | !VersionStack.empty() &&((!VersionStack.empty() && "Version stack should have liveOnEntry sentinel dominating everything" ) ? static_cast<void> (0) : __assert_fail ("!VersionStack.empty() && \"Version stack should have liveOnEntry sentinel dominating everything\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1367, __PRETTY_FUNCTION__)) | ||||
1367 | "Version stack should have liveOnEntry sentinel dominating everything")((!VersionStack.empty() && "Version stack should have liveOnEntry sentinel dominating everything" ) ? static_cast<void> (0) : __assert_fail ("!VersionStack.empty() && \"Version stack should have liveOnEntry sentinel dominating everything\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1367, __PRETTY_FUNCTION__)); | ||||
1368 | BasicBlock *BackBlock = VersionStack.back()->getBlock(); | ||||
1369 | if (DT->dominates(BackBlock, BB)) | ||||
1370 | break; | ||||
1371 | while (VersionStack.back()->getBlock() == BackBlock) | ||||
1372 | VersionStack.pop_back(); | ||||
1373 | ++PopEpoch; | ||||
1374 | } | ||||
1375 | |||||
1376 | for (MemoryAccess &MA : *Accesses) { | ||||
1377 | auto *MU = dyn_cast<MemoryUse>(&MA); | ||||
1378 | if (!MU) { | ||||
1379 | VersionStack.push_back(&MA); | ||||
1380 | ++StackEpoch; | ||||
1381 | continue; | ||||
1382 | } | ||||
1383 | |||||
1384 | if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) { | ||||
1385 | MU->setDefiningAccess(MSSA->getLiveOnEntryDef(), true, None); | ||||
1386 | continue; | ||||
1387 | } | ||||
1388 | |||||
1389 | MemoryLocOrCall UseMLOC(MU); | ||||
1390 | auto &LocInfo = LocStackInfo[UseMLOC]; | ||||
1391 | // If the pop epoch changed, it means we've removed stuff from top of | ||||
1392 | // stack due to changing blocks. We may have to reset the lower bound or | ||||
1393 | // last kill info. | ||||
1394 | if (LocInfo.PopEpoch != PopEpoch) { | ||||
1395 | LocInfo.PopEpoch = PopEpoch; | ||||
1396 | LocInfo.StackEpoch = StackEpoch; | ||||
1397 | // If the lower bound was in something that no longer dominates us, we | ||||
1398 | // have to reset it. | ||||
1399 | // We can't simply track stack size, because the stack may have had | ||||
1400 | // pushes/pops in the meantime. | ||||
1401 | // XXX: This is non-optimal, but only is slower cases with heavily | ||||
1402 | // branching dominator trees. To get the optimal number of queries would | ||||
1403 | // be to make lowerbound and lastkill a per-loc stack, and pop it until | ||||
1404 | // the top of that stack dominates us. This does not seem worth it ATM. | ||||
1405 | // A much cheaper optimization would be to always explore the deepest | ||||
1406 | // branch of the dominator tree first. This will guarantee this resets on | ||||
1407 | // the smallest set of blocks. | ||||
1408 | if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB && | ||||
1409 | !DT->dominates(LocInfo.LowerBoundBlock, BB)) { | ||||
1410 | // Reset the lower bound of things to check. | ||||
1411 | // TODO: Some day we should be able to reset to last kill, rather than | ||||
1412 | // 0. | ||||
1413 | LocInfo.LowerBound = 0; | ||||
1414 | LocInfo.LowerBoundBlock = VersionStack[0]->getBlock(); | ||||
1415 | LocInfo.LastKillValid = false; | ||||
1416 | } | ||||
1417 | } else if (LocInfo.StackEpoch != StackEpoch) { | ||||
1418 | // If all that has changed is the StackEpoch, we only have to check the | ||||
1419 | // new things on the stack, because we've checked everything before. In | ||||
1420 | // this case, the lower bound of things to check remains the same. | ||||
1421 | LocInfo.PopEpoch = PopEpoch; | ||||
1422 | LocInfo.StackEpoch = StackEpoch; | ||||
1423 | } | ||||
1424 | if (!LocInfo.LastKillValid) { | ||||
1425 | LocInfo.LastKill = VersionStack.size() - 1; | ||||
1426 | LocInfo.LastKillValid = true; | ||||
1427 | LocInfo.AR = MayAlias; | ||||
1428 | } | ||||
1429 | |||||
1430 | // At this point, we should have corrected last kill and LowerBound to be | ||||
1431 | // in bounds. | ||||
1432 | assert(LocInfo.LowerBound < VersionStack.size() &&((LocInfo.LowerBound < VersionStack.size() && "Lower bound out of range" ) ? static_cast<void> (0) : __assert_fail ("LocInfo.LowerBound < VersionStack.size() && \"Lower bound out of range\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1433, __PRETTY_FUNCTION__)) | ||||
1433 | "Lower bound out of range")((LocInfo.LowerBound < VersionStack.size() && "Lower bound out of range" ) ? static_cast<void> (0) : __assert_fail ("LocInfo.LowerBound < VersionStack.size() && \"Lower bound out of range\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1433, __PRETTY_FUNCTION__)); | ||||
1434 | assert(LocInfo.LastKill < VersionStack.size() &&((LocInfo.LastKill < VersionStack.size() && "Last kill info out of range" ) ? static_cast<void> (0) : __assert_fail ("LocInfo.LastKill < VersionStack.size() && \"Last kill info out of range\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1435, __PRETTY_FUNCTION__)) | ||||
1435 | "Last kill info out of range")((LocInfo.LastKill < VersionStack.size() && "Last kill info out of range" ) ? static_cast<void> (0) : __assert_fail ("LocInfo.LastKill < VersionStack.size() && \"Last kill info out of range\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1435, __PRETTY_FUNCTION__)); | ||||
1436 | // In any case, the new upper bound is the top of the stack. | ||||
1437 | unsigned long UpperBound = VersionStack.size() - 1; | ||||
1438 | |||||
1439 | if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) { | ||||
1440 | LLVM_DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memoryssa")) { dbgs() << "MemorySSA skipping optimization of " << *MU << " (" << *(MU->getMemoryInst() ) << ")" << " because there are " << UpperBound - LocInfo.LowerBound << " stores to disambiguate\n"; } } while (false) | ||||
1441 | << *(MU->getMemoryInst()) << ")"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memoryssa")) { dbgs() << "MemorySSA skipping optimization of " << *MU << " (" << *(MU->getMemoryInst() ) << ")" << " because there are " << UpperBound - LocInfo.LowerBound << " stores to disambiguate\n"; } } while (false) | ||||
1442 | << " because there are "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memoryssa")) { dbgs() << "MemorySSA skipping optimization of " << *MU << " (" << *(MU->getMemoryInst() ) << ")" << " because there are " << UpperBound - LocInfo.LowerBound << " stores to disambiguate\n"; } } while (false) | ||||
1443 | << UpperBound - LocInfo.LowerBounddo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memoryssa")) { dbgs() << "MemorySSA skipping optimization of " << *MU << " (" << *(MU->getMemoryInst() ) << ")" << " because there are " << UpperBound - LocInfo.LowerBound << " stores to disambiguate\n"; } } while (false) | ||||
1444 | << " stores to disambiguate\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memoryssa")) { dbgs() << "MemorySSA skipping optimization of " << *MU << " (" << *(MU->getMemoryInst() ) << ")" << " because there are " << UpperBound - LocInfo.LowerBound << " stores to disambiguate\n"; } } while (false); | ||||
1445 | // Because we did not walk, LastKill is no longer valid, as this may | ||||
1446 | // have been a kill. | ||||
1447 | LocInfo.LastKillValid = false; | ||||
1448 | continue; | ||||
1449 | } | ||||
1450 | bool FoundClobberResult = false; | ||||
1451 | unsigned UpwardWalkLimit = MaxCheckLimit; | ||||
1452 | while (UpperBound > LocInfo.LowerBound) { | ||||
1453 | if (isa<MemoryPhi>(VersionStack[UpperBound])) { | ||||
1454 | // For phis, use the walker, see where we ended up, go there | ||||
1455 | MemoryAccess *Result = | ||||
1456 | Walker->getClobberingMemoryAccess(MU, UpwardWalkLimit); | ||||
1457 | // We are guaranteed to find it or something is wrong | ||||
1458 | while (VersionStack[UpperBound] != Result) { | ||||
1459 | assert(UpperBound != 0)((UpperBound != 0) ? static_cast<void> (0) : __assert_fail ("UpperBound != 0", "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1459, __PRETTY_FUNCTION__)); | ||||
1460 | --UpperBound; | ||||
1461 | } | ||||
1462 | FoundClobberResult = true; | ||||
1463 | break; | ||||
1464 | } | ||||
1465 | |||||
1466 | MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]); | ||||
1467 | // If the lifetime of the pointer ends at this instruction, it's live on | ||||
1468 | // entry. | ||||
1469 | if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) { | ||||
1470 | // Reset UpperBound to liveOnEntryDef's place in the stack | ||||
1471 | UpperBound = 0; | ||||
1472 | FoundClobberResult = true; | ||||
1473 | LocInfo.AR = MustAlias; | ||||
1474 | break; | ||||
1475 | } | ||||
1476 | ClobberAlias CA = instructionClobbersQuery(MD, MU, UseMLOC, *AA); | ||||
1477 | if (CA.IsClobber) { | ||||
1478 | FoundClobberResult = true; | ||||
1479 | LocInfo.AR = CA.AR; | ||||
1480 | break; | ||||
1481 | } | ||||
1482 | --UpperBound; | ||||
1483 | } | ||||
1484 | |||||
1485 | // Note: Phis always have AliasResult AR set to MayAlias ATM. | ||||
1486 | |||||
1487 | // At the end of this loop, UpperBound is either a clobber, or lower bound | ||||
1488 | // PHI walking may cause it to be < LowerBound, and in fact, < LastKill. | ||||
1489 | if (FoundClobberResult || UpperBound < LocInfo.LastKill) { | ||||
1490 | // We were last killed now by where we got to | ||||
1491 | if (MSSA->isLiveOnEntryDef(VersionStack[UpperBound])) | ||||
1492 | LocInfo.AR = None; | ||||
1493 | MU->setDefiningAccess(VersionStack[UpperBound], true, LocInfo.AR); | ||||
1494 | LocInfo.LastKill = UpperBound; | ||||
1495 | } else { | ||||
1496 | // Otherwise, we checked all the new ones, and now we know we can get to | ||||
1497 | // LastKill. | ||||
1498 | MU->setDefiningAccess(VersionStack[LocInfo.LastKill], true, LocInfo.AR); | ||||
1499 | } | ||||
1500 | LocInfo.LowerBound = VersionStack.size() - 1; | ||||
1501 | LocInfo.LowerBoundBlock = BB; | ||||
1502 | } | ||||
1503 | } | ||||
1504 | |||||
1505 | /// Optimize uses to point to their actual clobbering definitions. | ||||
1506 | void MemorySSA::OptimizeUses::optimizeUses() { | ||||
1507 | SmallVector<MemoryAccess *, 16> VersionStack; | ||||
1508 | DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo; | ||||
1509 | VersionStack.push_back(MSSA->getLiveOnEntryDef()); | ||||
1510 | |||||
1511 | unsigned long StackEpoch = 1; | ||||
1512 | unsigned long PopEpoch = 1; | ||||
1513 | // We perform a non-recursive top-down dominator tree walk. | ||||
1514 | for (const auto *DomNode : depth_first(DT->getRootNode())) | ||||
1515 | optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack, | ||||
1516 | LocStackInfo); | ||||
1517 | } | ||||
1518 | |||||
1519 | void MemorySSA::placePHINodes( | ||||
1520 | const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks) { | ||||
1521 | // Determine where our MemoryPhi's should go | ||||
1522 | ForwardIDFCalculator IDFs(*DT); | ||||
1523 | IDFs.setDefiningBlocks(DefiningBlocks); | ||||
1524 | SmallVector<BasicBlock *, 32> IDFBlocks; | ||||
1525 | IDFs.calculate(IDFBlocks); | ||||
1526 | |||||
1527 | // Now place MemoryPhi nodes. | ||||
1528 | for (auto &BB : IDFBlocks) | ||||
1529 | createMemoryPhi(BB); | ||||
1530 | } | ||||
1531 | |||||
1532 | void MemorySSA::buildMemorySSA(BatchAAResults &BAA) { | ||||
1533 | // We create an access to represent "live on entry", for things like | ||||
1534 | // arguments or users of globals, where the memory they use is defined before | ||||
1535 | // the beginning of the function. We do not actually insert it into the IR. | ||||
1536 | // We do not define a live on exit for the immediate uses, and thus our | ||||
1537 | // semantics do *not* imply that something with no immediate uses can simply | ||||
1538 | // be removed. | ||||
1539 | BasicBlock &StartingPoint = F.getEntryBlock(); | ||||
1540 | LiveOnEntryDef.reset(new MemoryDef(F.getContext(), nullptr, nullptr, | ||||
1541 | &StartingPoint, NextID++)); | ||||
1542 | |||||
1543 | // We maintain lists of memory accesses per-block, trading memory for time. We | ||||
1544 | // could just look up the memory access for every possible instruction in the | ||||
1545 | // stream. | ||||
1546 | SmallPtrSet<BasicBlock *, 32> DefiningBlocks; | ||||
1547 | // Go through each block, figure out where defs occur, and chain together all | ||||
1548 | // the accesses. | ||||
1549 | for (BasicBlock &B : F) { | ||||
1550 | bool InsertIntoDef = false; | ||||
1551 | AccessList *Accesses = nullptr; | ||||
1552 | DefsList *Defs = nullptr; | ||||
1553 | for (Instruction &I : B) { | ||||
1554 | MemoryUseOrDef *MUD = createNewAccess(&I, &BAA); | ||||
1555 | if (!MUD) | ||||
1556 | continue; | ||||
1557 | |||||
1558 | if (!Accesses) | ||||
1559 | Accesses = getOrCreateAccessList(&B); | ||||
1560 | Accesses->push_back(MUD); | ||||
1561 | if (isa<MemoryDef>(MUD)) { | ||||
1562 | InsertIntoDef = true; | ||||
1563 | if (!Defs) | ||||
1564 | Defs = getOrCreateDefsList(&B); | ||||
1565 | Defs->push_back(*MUD); | ||||
1566 | } | ||||
1567 | } | ||||
1568 | if (InsertIntoDef) | ||||
1569 | DefiningBlocks.insert(&B); | ||||
1570 | } | ||||
1571 | placePHINodes(DefiningBlocks); | ||||
1572 | |||||
1573 | // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get | ||||
1574 | // filled in with all blocks. | ||||
1575 | SmallPtrSet<BasicBlock *, 16> Visited; | ||||
1576 | renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited); | ||||
1577 | |||||
1578 | ClobberWalkerBase<BatchAAResults> WalkerBase(this, &BAA, DT); | ||||
1579 | CachingWalker<BatchAAResults> WalkerLocal(this, &WalkerBase); | ||||
1580 | OptimizeUses(this, &WalkerLocal, &BAA, DT).optimizeUses(); | ||||
1581 | |||||
1582 | // Mark the uses in unreachable blocks as live on entry, so that they go | ||||
1583 | // somewhere. | ||||
1584 | for (auto &BB : F) | ||||
1585 | if (!Visited.count(&BB)) | ||||
1586 | markUnreachableAsLiveOnEntry(&BB); | ||||
1587 | } | ||||
1588 | |||||
1589 | MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); } | ||||
1590 | |||||
1591 | MemorySSA::CachingWalker<AliasAnalysis> *MemorySSA::getWalkerImpl() { | ||||
1592 | if (Walker) | ||||
1593 | return Walker.get(); | ||||
1594 | |||||
1595 | if (!WalkerBase) | ||||
1596 | WalkerBase = | ||||
1597 | std::make_unique<ClobberWalkerBase<AliasAnalysis>>(this, AA, DT); | ||||
1598 | |||||
1599 | Walker = | ||||
1600 | std::make_unique<CachingWalker<AliasAnalysis>>(this, WalkerBase.get()); | ||||
1601 | return Walker.get(); | ||||
1602 | } | ||||
1603 | |||||
1604 | MemorySSAWalker *MemorySSA::getSkipSelfWalker() { | ||||
1605 | if (SkipWalker) | ||||
1606 | return SkipWalker.get(); | ||||
1607 | |||||
1608 | if (!WalkerBase) | ||||
1609 | WalkerBase = | ||||
1610 | std::make_unique<ClobberWalkerBase<AliasAnalysis>>(this, AA, DT); | ||||
1611 | |||||
1612 | SkipWalker = | ||||
1613 | std::make_unique<SkipSelfWalker<AliasAnalysis>>(this, WalkerBase.get()); | ||||
1614 | return SkipWalker.get(); | ||||
1615 | } | ||||
1616 | |||||
1617 | |||||
1618 | // This is a helper function used by the creation routines. It places NewAccess | ||||
1619 | // into the access and defs lists for a given basic block, at the given | ||||
1620 | // insertion point. | ||||
1621 | void MemorySSA::insertIntoListsForBlock(MemoryAccess *NewAccess, | ||||
1622 | const BasicBlock *BB, | ||||
1623 | InsertionPlace Point) { | ||||
1624 | auto *Accesses = getOrCreateAccessList(BB); | ||||
1625 | if (Point == Beginning) { | ||||
1626 | // If it's a phi node, it goes first, otherwise, it goes after any phi | ||||
1627 | // nodes. | ||||
1628 | if (isa<MemoryPhi>(NewAccess)) { | ||||
1629 | Accesses->push_front(NewAccess); | ||||
1630 | auto *Defs = getOrCreateDefsList(BB); | ||||
1631 | Defs->push_front(*NewAccess); | ||||
1632 | } else { | ||||
1633 | auto AI = find_if_not( | ||||
1634 | *Accesses, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); }); | ||||
1635 | Accesses->insert(AI, NewAccess); | ||||
1636 | if (!isa<MemoryUse>(NewAccess)) { | ||||
1637 | auto *Defs = getOrCreateDefsList(BB); | ||||
1638 | auto DI = find_if_not( | ||||
1639 | *Defs, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); }); | ||||
1640 | Defs->insert(DI, *NewAccess); | ||||
1641 | } | ||||
1642 | } | ||||
1643 | } else { | ||||
1644 | Accesses->push_back(NewAccess); | ||||
1645 | if (!isa<MemoryUse>(NewAccess)) { | ||||
1646 | auto *Defs = getOrCreateDefsList(BB); | ||||
1647 | Defs->push_back(*NewAccess); | ||||
1648 | } | ||||
1649 | } | ||||
1650 | BlockNumberingValid.erase(BB); | ||||
1651 | } | ||||
1652 | |||||
1653 | void MemorySSA::insertIntoListsBefore(MemoryAccess *What, const BasicBlock *BB, | ||||
1654 | AccessList::iterator InsertPt) { | ||||
1655 | auto *Accesses = getWritableBlockAccesses(BB); | ||||
1656 | bool WasEnd = InsertPt == Accesses->end(); | ||||
1657 | Accesses->insert(AccessList::iterator(InsertPt), What); | ||||
1658 | if (!isa<MemoryUse>(What)) { | ||||
1659 | auto *Defs = getOrCreateDefsList(BB); | ||||
1660 | // If we got asked to insert at the end, we have an easy job, just shove it | ||||
1661 | // at the end. If we got asked to insert before an existing def, we also get | ||||
1662 | // an iterator. If we got asked to insert before a use, we have to hunt for | ||||
1663 | // the next def. | ||||
1664 | if (WasEnd) { | ||||
1665 | Defs->push_back(*What); | ||||
1666 | } else if (isa<MemoryDef>(InsertPt)) { | ||||
1667 | Defs->insert(InsertPt->getDefsIterator(), *What); | ||||
1668 | } else { | ||||
1669 | while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt)) | ||||
1670 | ++InsertPt; | ||||
1671 | // Either we found a def, or we are inserting at the end | ||||
1672 | if (InsertPt == Accesses->end()) | ||||
1673 | Defs->push_back(*What); | ||||
1674 | else | ||||
1675 | Defs->insert(InsertPt->getDefsIterator(), *What); | ||||
1676 | } | ||||
1677 | } | ||||
1678 | BlockNumberingValid.erase(BB); | ||||
1679 | } | ||||
1680 | |||||
1681 | void MemorySSA::prepareForMoveTo(MemoryAccess *What, BasicBlock *BB) { | ||||
1682 | // Keep it in the lookup tables, remove from the lists | ||||
1683 | removeFromLists(What, false); | ||||
1684 | |||||
1685 | // Note that moving should implicitly invalidate the optimized state of a | ||||
1686 | // MemoryUse (and Phis can't be optimized). However, it doesn't do so for a | ||||
1687 | // MemoryDef. | ||||
1688 | if (auto *MD = dyn_cast<MemoryDef>(What)) | ||||
1689 | MD->resetOptimized(); | ||||
1690 | What->setBlock(BB); | ||||
1691 | } | ||||
1692 | |||||
1693 | // Move What before Where in the IR. The end result is that What will belong to | ||||
1694 | // the right lists and have the right Block set, but will not otherwise be | ||||
1695 | // correct. It will not have the right defining access, and if it is a def, | ||||
1696 | // things below it will not properly be updated. | ||||
1697 | void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB, | ||||
1698 | AccessList::iterator Where) { | ||||
1699 | prepareForMoveTo(What, BB); | ||||
1700 | insertIntoListsBefore(What, BB, Where); | ||||
1701 | } | ||||
1702 | |||||
1703 | void MemorySSA::moveTo(MemoryAccess *What, BasicBlock *BB, | ||||
1704 | InsertionPlace Point) { | ||||
1705 | if (isa<MemoryPhi>(What)) { | ||||
1706 | assert(Point == Beginning &&((Point == Beginning && "Can only move a Phi at the beginning of the block" ) ? static_cast<void> (0) : __assert_fail ("Point == Beginning && \"Can only move a Phi at the beginning of the block\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1707, __PRETTY_FUNCTION__)) | ||||
1707 | "Can only move a Phi at the beginning of the block")((Point == Beginning && "Can only move a Phi at the beginning of the block" ) ? static_cast<void> (0) : __assert_fail ("Point == Beginning && \"Can only move a Phi at the beginning of the block\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1707, __PRETTY_FUNCTION__)); | ||||
1708 | // Update lookup table entry | ||||
1709 | ValueToMemoryAccess.erase(What->getBlock()); | ||||
1710 | bool Inserted = ValueToMemoryAccess.insert({BB, What}).second; | ||||
1711 | (void)Inserted; | ||||
1712 | assert(Inserted && "Cannot move a Phi to a block that already has one")((Inserted && "Cannot move a Phi to a block that already has one" ) ? static_cast<void> (0) : __assert_fail ("Inserted && \"Cannot move a Phi to a block that already has one\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1712, __PRETTY_FUNCTION__)); | ||||
1713 | } | ||||
1714 | |||||
1715 | prepareForMoveTo(What, BB); | ||||
1716 | insertIntoListsForBlock(What, BB, Point); | ||||
1717 | } | ||||
1718 | |||||
1719 | MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) { | ||||
1720 | assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB")((!getMemoryAccess(BB) && "MemoryPhi already exists for this BB" ) ? static_cast<void> (0) : __assert_fail ("!getMemoryAccess(BB) && \"MemoryPhi already exists for this BB\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1720, __PRETTY_FUNCTION__)); | ||||
1721 | MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++); | ||||
1722 | // Phi's always are placed at the front of the block. | ||||
1723 | insertIntoListsForBlock(Phi, BB, Beginning); | ||||
1724 | ValueToMemoryAccess[BB] = Phi; | ||||
1725 | return Phi; | ||||
1726 | } | ||||
1727 | |||||
1728 | MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I, | ||||
1729 | MemoryAccess *Definition, | ||||
1730 | const MemoryUseOrDef *Template, | ||||
1731 | bool CreationMustSucceed) { | ||||
1732 | assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI")((!isa<PHINode>(I) && "Cannot create a defined access for a PHI" ) ? static_cast<void> (0) : __assert_fail ("!isa<PHINode>(I) && \"Cannot create a defined access for a PHI\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1732, __PRETTY_FUNCTION__)); | ||||
1733 | MemoryUseOrDef *NewAccess = createNewAccess(I, AA, Template); | ||||
1734 | if (CreationMustSucceed) | ||||
1735 | assert(NewAccess != nullptr && "Tried to create a memory access for a "((NewAccess != nullptr && "Tried to create a memory access for a " "non-memory touching instruction") ? static_cast<void> (0) : __assert_fail ("NewAccess != nullptr && \"Tried to create a memory access for a \" \"non-memory touching instruction\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1736, __PRETTY_FUNCTION__)) | ||||
1736 | "non-memory touching instruction")((NewAccess != nullptr && "Tried to create a memory access for a " "non-memory touching instruction") ? static_cast<void> (0) : __assert_fail ("NewAccess != nullptr && \"Tried to create a memory access for a \" \"non-memory touching instruction\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1736, __PRETTY_FUNCTION__)); | ||||
1737 | if (NewAccess) { | ||||
1738 | assert((!Definition || !isa<MemoryUse>(Definition)) &&(((!Definition || !isa<MemoryUse>(Definition)) && "A use cannot be a defining access") ? static_cast<void> (0) : __assert_fail ("(!Definition || !isa<MemoryUse>(Definition)) && \"A use cannot be a defining access\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1739, __PRETTY_FUNCTION__)) | ||||
1739 | "A use cannot be a defining access")(((!Definition || !isa<MemoryUse>(Definition)) && "A use cannot be a defining access") ? static_cast<void> (0) : __assert_fail ("(!Definition || !isa<MemoryUse>(Definition)) && \"A use cannot be a defining access\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1739, __PRETTY_FUNCTION__)); | ||||
1740 | NewAccess->setDefiningAccess(Definition); | ||||
1741 | } | ||||
1742 | return NewAccess; | ||||
1743 | } | ||||
1744 | |||||
1745 | // Return true if the instruction has ordering constraints. | ||||
1746 | // Note specifically that this only considers stores and loads | ||||
1747 | // because others are still considered ModRef by getModRefInfo. | ||||
1748 | static inline bool isOrdered(const Instruction *I) { | ||||
1749 | if (auto *SI = dyn_cast<StoreInst>(I)) { | ||||
1750 | if (!SI->isUnordered()) | ||||
1751 | return true; | ||||
1752 | } else if (auto *LI = dyn_cast<LoadInst>(I)) { | ||||
1753 | if (!LI->isUnordered()) | ||||
1754 | return true; | ||||
1755 | } | ||||
1756 | return false; | ||||
1757 | } | ||||
1758 | |||||
1759 | /// Helper function to create new memory accesses | ||||
1760 | template <typename AliasAnalysisType> | ||||
1761 | MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I, | ||||
1762 | AliasAnalysisType *AAP, | ||||
1763 | const MemoryUseOrDef *Template) { | ||||
1764 | // The assume intrinsic has a control dependency which we model by claiming | ||||
1765 | // that it writes arbitrarily. Debuginfo intrinsics may be considered | ||||
1766 | // clobbers when we have a nonstandard AA pipeline. Ignore these fake memory | ||||
1767 | // dependencies here. | ||||
1768 | // FIXME: Replace this special casing with a more accurate modelling of | ||||
1769 | // assume's control dependency. | ||||
1770 | if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) | ||||
1771 | if (II->getIntrinsicID() == Intrinsic::assume) | ||||
1772 | return nullptr; | ||||
1773 | |||||
1774 | // Using a nonstandard AA pipelines might leave us with unexpected modref | ||||
1775 | // results for I, so add a check to not model instructions that may not read | ||||
1776 | // from or write to memory. This is necessary for correctness. | ||||
1777 | if (!I->mayReadFromMemory() && !I->mayWriteToMemory()) | ||||
1778 | return nullptr; | ||||
1779 | |||||
1780 | bool Def, Use; | ||||
1781 | if (Template) { | ||||
1782 | Def = dyn_cast_or_null<MemoryDef>(Template) != nullptr; | ||||
1783 | Use = dyn_cast_or_null<MemoryUse>(Template) != nullptr; | ||||
1784 | #if !defined(NDEBUG) | ||||
1785 | ModRefInfo ModRef = AAP->getModRefInfo(I, None); | ||||
1786 | bool DefCheck, UseCheck; | ||||
1787 | DefCheck = isModSet(ModRef) || isOrdered(I); | ||||
1788 | UseCheck = isRefSet(ModRef); | ||||
1789 | assert(Def == DefCheck && (Def || Use == UseCheck) && "Invalid template")((Def == DefCheck && (Def || Use == UseCheck) && "Invalid template") ? static_cast<void> (0) : __assert_fail ("Def == DefCheck && (Def || Use == UseCheck) && \"Invalid template\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1789, __PRETTY_FUNCTION__)); | ||||
1790 | #endif | ||||
1791 | } else { | ||||
1792 | // Find out what affect this instruction has on memory. | ||||
1793 | ModRefInfo ModRef = AAP->getModRefInfo(I, None); | ||||
1794 | // The isOrdered check is used to ensure that volatiles end up as defs | ||||
1795 | // (atomics end up as ModRef right now anyway). Until we separate the | ||||
1796 | // ordering chain from the memory chain, this enables people to see at least | ||||
1797 | // some relative ordering to volatiles. Note that getClobberingMemoryAccess | ||||
1798 | // will still give an answer that bypasses other volatile loads. TODO: | ||||
1799 | // Separate memory aliasing and ordering into two different chains so that | ||||
1800 | // we can precisely represent both "what memory will this read/write/is | ||||
1801 | // clobbered by" and "what instructions can I move this past". | ||||
1802 | Def = isModSet(ModRef) || isOrdered(I); | ||||
1803 | Use = isRefSet(ModRef); | ||||
1804 | } | ||||
1805 | |||||
1806 | // It's possible for an instruction to not modify memory at all. During | ||||
1807 | // construction, we ignore them. | ||||
1808 | if (!Def && !Use) | ||||
1809 | return nullptr; | ||||
1810 | |||||
1811 | MemoryUseOrDef *MUD; | ||||
1812 | if (Def) | ||||
1813 | MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++); | ||||
1814 | else | ||||
1815 | MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent()); | ||||
1816 | ValueToMemoryAccess[I] = MUD; | ||||
1817 | return MUD; | ||||
1818 | } | ||||
1819 | |||||
1820 | /// Returns true if \p Replacer dominates \p Replacee . | ||||
1821 | bool MemorySSA::dominatesUse(const MemoryAccess *Replacer, | ||||
1822 | const MemoryAccess *Replacee) const { | ||||
1823 | if (isa<MemoryUseOrDef>(Replacee)) | ||||
1824 | return DT->dominates(Replacer->getBlock(), Replacee->getBlock()); | ||||
1825 | const auto *MP = cast<MemoryPhi>(Replacee); | ||||
1826 | // For a phi node, the use occurs in the predecessor block of the phi node. | ||||
1827 | // Since we may occur multiple times in the phi node, we have to check each | ||||
1828 | // operand to ensure Replacer dominates each operand where Replacee occurs. | ||||
1829 | for (const Use &Arg : MP->operands()) { | ||||
1830 | if (Arg.get() != Replacee && | ||||
1831 | !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg))) | ||||
1832 | return false; | ||||
1833 | } | ||||
1834 | return true; | ||||
1835 | } | ||||
1836 | |||||
1837 | /// Properly remove \p MA from all of MemorySSA's lookup tables. | ||||
1838 | void MemorySSA::removeFromLookups(MemoryAccess *MA) { | ||||
1839 | assert(MA->use_empty() &&((MA->use_empty() && "Trying to remove memory access that still has uses" ) ? static_cast<void> (0) : __assert_fail ("MA->use_empty() && \"Trying to remove memory access that still has uses\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1840, __PRETTY_FUNCTION__)) | ||||
1840 | "Trying to remove memory access that still has uses")((MA->use_empty() && "Trying to remove memory access that still has uses" ) ? static_cast<void> (0) : __assert_fail ("MA->use_empty() && \"Trying to remove memory access that still has uses\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1840, __PRETTY_FUNCTION__)); | ||||
1841 | BlockNumbering.erase(MA); | ||||
1842 | if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) | ||||
1843 | MUD->setDefiningAccess(nullptr); | ||||
1844 | // Invalidate our walker's cache if necessary | ||||
1845 | if (!isa<MemoryUse>(MA)) | ||||
1846 | getWalker()->invalidateInfo(MA); | ||||
1847 | |||||
1848 | Value *MemoryInst; | ||||
1849 | if (const auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) | ||||
1850 | MemoryInst = MUD->getMemoryInst(); | ||||
1851 | else | ||||
1852 | MemoryInst = MA->getBlock(); | ||||
1853 | |||||
1854 | auto VMA = ValueToMemoryAccess.find(MemoryInst); | ||||
1855 | if (VMA->second == MA) | ||||
1856 | ValueToMemoryAccess.erase(VMA); | ||||
1857 | } | ||||
1858 | |||||
1859 | /// Properly remove \p MA from all of MemorySSA's lists. | ||||
1860 | /// | ||||
1861 | /// Because of the way the intrusive list and use lists work, it is important to | ||||
1862 | /// do removal in the right order. | ||||
1863 | /// ShouldDelete defaults to true, and will cause the memory access to also be | ||||
1864 | /// deleted, not just removed. | ||||
1865 | void MemorySSA::removeFromLists(MemoryAccess *MA, bool ShouldDelete) { | ||||
1866 | BasicBlock *BB = MA->getBlock(); | ||||
1867 | // The access list owns the reference, so we erase it from the non-owning list | ||||
1868 | // first. | ||||
1869 | if (!isa<MemoryUse>(MA)) { | ||||
1870 | auto DefsIt = PerBlockDefs.find(BB); | ||||
1871 | std::unique_ptr<DefsList> &Defs = DefsIt->second; | ||||
1872 | Defs->remove(*MA); | ||||
1873 | if (Defs->empty()) | ||||
1874 | PerBlockDefs.erase(DefsIt); | ||||
1875 | } | ||||
1876 | |||||
1877 | // The erase call here will delete it. If we don't want it deleted, we call | ||||
1878 | // remove instead. | ||||
1879 | auto AccessIt = PerBlockAccesses.find(BB); | ||||
1880 | std::unique_ptr<AccessList> &Accesses = AccessIt->second; | ||||
1881 | if (ShouldDelete) | ||||
1882 | Accesses->erase(MA); | ||||
1883 | else | ||||
1884 | Accesses->remove(MA); | ||||
1885 | |||||
1886 | if (Accesses->empty()) { | ||||
1887 | PerBlockAccesses.erase(AccessIt); | ||||
1888 | BlockNumberingValid.erase(BB); | ||||
1889 | } | ||||
1890 | } | ||||
1891 | |||||
1892 | void MemorySSA::print(raw_ostream &OS) const { | ||||
1893 | MemorySSAAnnotatedWriter Writer(this); | ||||
1894 | F.print(OS, &Writer); | ||||
1895 | } | ||||
1896 | |||||
1897 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) | ||||
1898 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void MemorySSA::dump() const { print(dbgs()); } | ||||
1899 | #endif | ||||
1900 | |||||
1901 | void MemorySSA::verifyMemorySSA() const { | ||||
1902 | verifyOrderingDominationAndDefUses(F); | ||||
1903 | verifyDominationNumbers(F); | ||||
1904 | verifyPrevDefInPhis(F); | ||||
1905 | // Previously, the verification used to also verify that the clobberingAccess | ||||
1906 | // cached by MemorySSA is the same as the clobberingAccess found at a later | ||||
1907 | // query to AA. This does not hold true in general due to the current fragility | ||||
1908 | // of BasicAA which has arbitrary caps on the things it analyzes before giving | ||||
1909 | // up. As a result, transformations that are correct, will lead to BasicAA | ||||
1910 | // returning different Alias answers before and after that transformation. | ||||
1911 | // Invalidating MemorySSA is not an option, as the results in BasicAA can be so | ||||
1912 | // random, in the worst case we'd need to rebuild MemorySSA from scratch after | ||||
1913 | // every transformation, which defeats the purpose of using it. For such an | ||||
1914 | // example, see test4 added in D51960. | ||||
1915 | } | ||||
1916 | |||||
1917 | void MemorySSA::verifyPrevDefInPhis(Function &F) const { | ||||
1918 | #if !defined(NDEBUG) && defined(EXPENSIVE_CHECKS) | ||||
1919 | for (const BasicBlock &BB : F) { | ||||
1920 | if (MemoryPhi *Phi = getMemoryAccess(&BB)) { | ||||
1921 | for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) { | ||||
1922 | auto *Pred = Phi->getIncomingBlock(I); | ||||
1923 | auto *IncAcc = Phi->getIncomingValue(I); | ||||
1924 | // If Pred has no unreachable predecessors, get last def looking at | ||||
1925 | // IDoms. If, while walkings IDoms, any of these has an unreachable | ||||
1926 | // predecessor, then the incoming def can be any access. | ||||
1927 | if (auto *DTNode = DT->getNode(Pred)) { | ||||
1928 | while (DTNode) { | ||||
1929 | if (auto *DefList = getBlockDefs(DTNode->getBlock())) { | ||||
1930 | auto *LastAcc = &*(--DefList->end()); | ||||
1931 | assert(LastAcc == IncAcc &&((LastAcc == IncAcc && "Incorrect incoming access into phi." ) ? static_cast<void> (0) : __assert_fail ("LastAcc == IncAcc && \"Incorrect incoming access into phi.\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1932, __PRETTY_FUNCTION__)) | ||||
1932 | "Incorrect incoming access into phi.")((LastAcc == IncAcc && "Incorrect incoming access into phi." ) ? static_cast<void> (0) : __assert_fail ("LastAcc == IncAcc && \"Incorrect incoming access into phi.\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1932, __PRETTY_FUNCTION__)); | ||||
1933 | break; | ||||
1934 | } | ||||
1935 | DTNode = DTNode->getIDom(); | ||||
1936 | } | ||||
1937 | } else { | ||||
1938 | // If Pred has unreachable predecessors, but has at least a Def, the | ||||
1939 | // incoming access can be the last Def in Pred, or it could have been | ||||
1940 | // optimized to LoE. After an update, though, the LoE may have been | ||||
1941 | // replaced by another access, so IncAcc may be any access. | ||||
1942 | // If Pred has unreachable predecessors and no Defs, incoming access | ||||
1943 | // should be LoE; However, after an update, it may be any access. | ||||
1944 | } | ||||
1945 | } | ||||
1946 | } | ||||
1947 | } | ||||
1948 | #endif | ||||
1949 | } | ||||
1950 | |||||
1951 | /// Verify that all of the blocks we believe to have valid domination numbers | ||||
1952 | /// actually have valid domination numbers. | ||||
1953 | void MemorySSA::verifyDominationNumbers(const Function &F) const { | ||||
1954 | #ifndef NDEBUG | ||||
1955 | if (BlockNumberingValid.empty()) | ||||
1956 | return; | ||||
1957 | |||||
1958 | SmallPtrSet<const BasicBlock *, 16> ValidBlocks = BlockNumberingValid; | ||||
1959 | for (const BasicBlock &BB : F) { | ||||
1960 | if (!ValidBlocks.count(&BB)) | ||||
1961 | continue; | ||||
1962 | |||||
1963 | ValidBlocks.erase(&BB); | ||||
1964 | |||||
1965 | const AccessList *Accesses = getBlockAccesses(&BB); | ||||
1966 | // It's correct to say an empty block has valid numbering. | ||||
1967 | if (!Accesses) | ||||
1968 | continue; | ||||
1969 | |||||
1970 | // Block numbering starts at 1. | ||||
1971 | unsigned long LastNumber = 0; | ||||
1972 | for (const MemoryAccess &MA : *Accesses) { | ||||
1973 | auto ThisNumberIter = BlockNumbering.find(&MA); | ||||
1974 | assert(ThisNumberIter != BlockNumbering.end() &&((ThisNumberIter != BlockNumbering.end() && "MemoryAccess has no domination number in a valid block!" ) ? static_cast<void> (0) : __assert_fail ("ThisNumberIter != BlockNumbering.end() && \"MemoryAccess has no domination number in a valid block!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1975, __PRETTY_FUNCTION__)) | ||||
1975 | "MemoryAccess has no domination number in a valid block!")((ThisNumberIter != BlockNumbering.end() && "MemoryAccess has no domination number in a valid block!" ) ? static_cast<void> (0) : __assert_fail ("ThisNumberIter != BlockNumbering.end() && \"MemoryAccess has no domination number in a valid block!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1975, __PRETTY_FUNCTION__)); | ||||
1976 | |||||
1977 | unsigned long ThisNumber = ThisNumberIter->second; | ||||
1978 | assert(ThisNumber > LastNumber &&((ThisNumber > LastNumber && "Domination numbers should be strictly increasing!" ) ? static_cast<void> (0) : __assert_fail ("ThisNumber > LastNumber && \"Domination numbers should be strictly increasing!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1979, __PRETTY_FUNCTION__)) | ||||
1979 | "Domination numbers should be strictly increasing!")((ThisNumber > LastNumber && "Domination numbers should be strictly increasing!" ) ? static_cast<void> (0) : __assert_fail ("ThisNumber > LastNumber && \"Domination numbers should be strictly increasing!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1979, __PRETTY_FUNCTION__)); | ||||
1980 | LastNumber = ThisNumber; | ||||
1981 | } | ||||
1982 | } | ||||
1983 | |||||
1984 | assert(ValidBlocks.empty() &&((ValidBlocks.empty() && "All valid BasicBlocks should exist in F -- dangling pointers?" ) ? static_cast<void> (0) : __assert_fail ("ValidBlocks.empty() && \"All valid BasicBlocks should exist in F -- dangling pointers?\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1985, __PRETTY_FUNCTION__)) | ||||
1985 | "All valid BasicBlocks should exist in F -- dangling pointers?")((ValidBlocks.empty() && "All valid BasicBlocks should exist in F -- dangling pointers?" ) ? static_cast<void> (0) : __assert_fail ("ValidBlocks.empty() && \"All valid BasicBlocks should exist in F -- dangling pointers?\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 1985, __PRETTY_FUNCTION__)); | ||||
1986 | #endif | ||||
1987 | } | ||||
1988 | |||||
1989 | /// Verify ordering: the order and existence of MemoryAccesses matches the | ||||
1990 | /// order and existence of memory affecting instructions. | ||||
1991 | /// Verify domination: each definition dominates all of its uses. | ||||
1992 | /// Verify def-uses: the immediate use information - walk all the memory | ||||
1993 | /// accesses and verifying that, for each use, it appears in the appropriate | ||||
1994 | /// def's use list | ||||
1995 | void MemorySSA::verifyOrderingDominationAndDefUses(Function &F) const { | ||||
1996 | #if !defined(NDEBUG) | ||||
1997 | // Walk all the blocks, comparing what the lookups think and what the access | ||||
1998 | // lists think, as well as the order in the blocks vs the order in the access | ||||
1999 | // lists. | ||||
2000 | SmallVector<MemoryAccess *, 32> ActualAccesses; | ||||
2001 | SmallVector<MemoryAccess *, 32> ActualDefs; | ||||
2002 | for (BasicBlock &B : F) { | ||||
2003 | const AccessList *AL = getBlockAccesses(&B); | ||||
2004 | const auto *DL = getBlockDefs(&B); | ||||
2005 | MemoryPhi *Phi = getMemoryAccess(&B); | ||||
2006 | if (Phi
| ||||
2007 | // Verify ordering. | ||||
2008 | ActualAccesses.push_back(Phi); | ||||
2009 | ActualDefs.push_back(Phi); | ||||
2010 | // Verify domination | ||||
2011 | for (const Use &U : Phi->uses()) | ||||
2012 | assert(dominates(Phi, U) && "Memory PHI does not dominate it's uses")((dominates(Phi, U) && "Memory PHI does not dominate it's uses" ) ? static_cast<void> (0) : __assert_fail ("dominates(Phi, U) && \"Memory PHI does not dominate it's uses\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2012, __PRETTY_FUNCTION__)); | ||||
2013 | #if defined(EXPENSIVE_CHECKS) | ||||
2014 | // Verify def-uses. | ||||
2015 | assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(((Phi->getNumOperands() == static_cast<unsigned>(std ::distance( pred_begin(&B), pred_end(&B))) && "Incomplete MemoryPhi Node") ? static_cast<void> (0) : __assert_fail ("Phi->getNumOperands() == static_cast<unsigned>(std::distance( pred_begin(&B), pred_end(&B))) && \"Incomplete MemoryPhi Node\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2017, __PRETTY_FUNCTION__)) | ||||
2016 | pred_begin(&B), pred_end(&B))) &&((Phi->getNumOperands() == static_cast<unsigned>(std ::distance( pred_begin(&B), pred_end(&B))) && "Incomplete MemoryPhi Node") ? static_cast<void> (0) : __assert_fail ("Phi->getNumOperands() == static_cast<unsigned>(std::distance( pred_begin(&B), pred_end(&B))) && \"Incomplete MemoryPhi Node\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2017, __PRETTY_FUNCTION__)) | ||||
2017 | "Incomplete MemoryPhi Node")((Phi->getNumOperands() == static_cast<unsigned>(std ::distance( pred_begin(&B), pred_end(&B))) && "Incomplete MemoryPhi Node") ? static_cast<void> (0) : __assert_fail ("Phi->getNumOperands() == static_cast<unsigned>(std::distance( pred_begin(&B), pred_end(&B))) && \"Incomplete MemoryPhi Node\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2017, __PRETTY_FUNCTION__)); | ||||
2018 | for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) { | ||||
2019 | verifyUseInDefs(Phi->getIncomingValue(I), Phi); | ||||
2020 | assert(find(predecessors(&B), Phi->getIncomingBlock(I)) !=((find(predecessors(&B), Phi->getIncomingBlock(I)) != pred_end (&B) && "Incoming phi block not a block predecessor" ) ? static_cast<void> (0) : __assert_fail ("find(predecessors(&B), Phi->getIncomingBlock(I)) != pred_end(&B) && \"Incoming phi block not a block predecessor\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2022, __PRETTY_FUNCTION__)) | ||||
2021 | pred_end(&B) &&((find(predecessors(&B), Phi->getIncomingBlock(I)) != pred_end (&B) && "Incoming phi block not a block predecessor" ) ? static_cast<void> (0) : __assert_fail ("find(predecessors(&B), Phi->getIncomingBlock(I)) != pred_end(&B) && \"Incoming phi block not a block predecessor\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2022, __PRETTY_FUNCTION__)) | ||||
2022 | "Incoming phi block not a block predecessor")((find(predecessors(&B), Phi->getIncomingBlock(I)) != pred_end (&B) && "Incoming phi block not a block predecessor" ) ? static_cast<void> (0) : __assert_fail ("find(predecessors(&B), Phi->getIncomingBlock(I)) != pred_end(&B) && \"Incoming phi block not a block predecessor\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2022, __PRETTY_FUNCTION__)); | ||||
2023 | } | ||||
2024 | #endif | ||||
2025 | } | ||||
2026 | |||||
2027 | for (Instruction &I : B) { | ||||
2028 | MemoryUseOrDef *MA = getMemoryAccess(&I); | ||||
2029 | assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) &&(((!MA || (AL && (isa<MemoryUse>(MA) || DL))) && "We have memory affecting instructions " "in this block but they are not in the " "access list or defs list") ? static_cast<void> (0) : __assert_fail ("(!MA || (AL && (isa<MemoryUse>(MA) || DL))) && \"We have memory affecting instructions \" \"in this block but they are not in the \" \"access list or defs list\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2032, __PRETTY_FUNCTION__)) | ||||
2030 | "We have memory affecting instructions "(((!MA || (AL && (isa<MemoryUse>(MA) || DL))) && "We have memory affecting instructions " "in this block but they are not in the " "access list or defs list") ? static_cast<void> (0) : __assert_fail ("(!MA || (AL && (isa<MemoryUse>(MA) || DL))) && \"We have memory affecting instructions \" \"in this block but they are not in the \" \"access list or defs list\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2032, __PRETTY_FUNCTION__)) | ||||
2031 | "in this block but they are not in the "(((!MA || (AL && (isa<MemoryUse>(MA) || DL))) && "We have memory affecting instructions " "in this block but they are not in the " "access list or defs list") ? static_cast<void> (0) : __assert_fail ("(!MA || (AL && (isa<MemoryUse>(MA) || DL))) && \"We have memory affecting instructions \" \"in this block but they are not in the \" \"access list or defs list\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2032, __PRETTY_FUNCTION__)) | ||||
2032 | "access list or defs list")(((!MA || (AL && (isa<MemoryUse>(MA) || DL))) && "We have memory affecting instructions " "in this block but they are not in the " "access list or defs list") ? static_cast<void> (0) : __assert_fail ("(!MA || (AL && (isa<MemoryUse>(MA) || DL))) && \"We have memory affecting instructions \" \"in this block but they are not in the \" \"access list or defs list\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2032, __PRETTY_FUNCTION__)); | ||||
2033 | if (MA) { | ||||
2034 | // Verify ordering. | ||||
2035 | ActualAccesses.push_back(MA); | ||||
2036 | if (MemoryAccess *MD = dyn_cast<MemoryDef>(MA)) { | ||||
2037 | // Verify ordering. | ||||
2038 | ActualDefs.push_back(MA); | ||||
2039 | // Verify domination. | ||||
2040 | for (const Use &U : MD->uses()) | ||||
2041 | assert(dominates(MD, U) &&((dominates(MD, U) && "Memory Def does not dominate it's uses" ) ? static_cast<void> (0) : __assert_fail ("dominates(MD, U) && \"Memory Def does not dominate it's uses\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2042, __PRETTY_FUNCTION__)) | ||||
2042 | "Memory Def does not dominate it's uses")((dominates(MD, U) && "Memory Def does not dominate it's uses" ) ? static_cast<void> (0) : __assert_fail ("dominates(MD, U) && \"Memory Def does not dominate it's uses\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2042, __PRETTY_FUNCTION__)); | ||||
2043 | } | ||||
2044 | #if defined(EXPENSIVE_CHECKS) | ||||
2045 | // Verify def-uses. | ||||
2046 | verifyUseInDefs(MA->getDefiningAccess(), MA); | ||||
2047 | #endif | ||||
2048 | } | ||||
2049 | } | ||||
2050 | // Either we hit the assert, really have no accesses, or we have both | ||||
2051 | // accesses and an access list. Same with defs. | ||||
2052 | if (!AL && !DL) | ||||
2053 | continue; | ||||
2054 | // Verify ordering. | ||||
2055 | assert(AL->size() == ActualAccesses.size() &&((AL->size() == ActualAccesses.size() && "We don't have the same number of accesses in the block as on the " "access list") ? static_cast<void> (0) : __assert_fail ("AL->size() == ActualAccesses.size() && \"We don't have the same number of accesses in the block as on the \" \"access list\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2057, __PRETTY_FUNCTION__)) | ||||
| |||||
2056 | "We don't have the same number of accesses in the block as on the "((AL->size() == ActualAccesses.size() && "We don't have the same number of accesses in the block as on the " "access list") ? static_cast<void> (0) : __assert_fail ("AL->size() == ActualAccesses.size() && \"We don't have the same number of accesses in the block as on the \" \"access list\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2057, __PRETTY_FUNCTION__)) | ||||
2057 | "access list")((AL->size() == ActualAccesses.size() && "We don't have the same number of accesses in the block as on the " "access list") ? static_cast<void> (0) : __assert_fail ("AL->size() == ActualAccesses.size() && \"We don't have the same number of accesses in the block as on the \" \"access list\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2057, __PRETTY_FUNCTION__)); | ||||
2058 | assert((DL || ActualDefs.size() == 0) &&(((DL || ActualDefs.size() == 0) && "Either we should have a defs list, or we should have no defs" ) ? static_cast<void> (0) : __assert_fail ("(DL || ActualDefs.size() == 0) && \"Either we should have a defs list, or we should have no defs\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2059, __PRETTY_FUNCTION__)) | ||||
2059 | "Either we should have a defs list, or we should have no defs")(((DL || ActualDefs.size() == 0) && "Either we should have a defs list, or we should have no defs" ) ? static_cast<void> (0) : __assert_fail ("(DL || ActualDefs.size() == 0) && \"Either we should have a defs list, or we should have no defs\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2059, __PRETTY_FUNCTION__)); | ||||
2060 | assert((!DL || DL->size() == ActualDefs.size()) &&(((!DL || DL->size() == ActualDefs.size()) && "We don't have the same number of defs in the block as on the " "def list") ? static_cast<void> (0) : __assert_fail ("(!DL || DL->size() == ActualDefs.size()) && \"We don't have the same number of defs in the block as on the \" \"def list\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2062, __PRETTY_FUNCTION__)) | ||||
2061 | "We don't have the same number of defs in the block as on the "(((!DL || DL->size() == ActualDefs.size()) && "We don't have the same number of defs in the block as on the " "def list") ? static_cast<void> (0) : __assert_fail ("(!DL || DL->size() == ActualDefs.size()) && \"We don't have the same number of defs in the block as on the \" \"def list\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2062, __PRETTY_FUNCTION__)) | ||||
2062 | "def list")(((!DL || DL->size() == ActualDefs.size()) && "We don't have the same number of defs in the block as on the " "def list") ? static_cast<void> (0) : __assert_fail ("(!DL || DL->size() == ActualDefs.size()) && \"We don't have the same number of defs in the block as on the \" \"def list\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2062, __PRETTY_FUNCTION__)); | ||||
2063 | auto ALI = AL->begin(); | ||||
2064 | auto AAI = ActualAccesses.begin(); | ||||
2065 | while (ALI != AL->end() && AAI != ActualAccesses.end()) { | ||||
2066 | assert(&*ALI == *AAI && "Not the same accesses in the same order")((&*ALI == *AAI && "Not the same accesses in the same order" ) ? static_cast<void> (0) : __assert_fail ("&*ALI == *AAI && \"Not the same accesses in the same order\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2066, __PRETTY_FUNCTION__)); | ||||
2067 | ++ALI; | ||||
2068 | ++AAI; | ||||
2069 | } | ||||
2070 | ActualAccesses.clear(); | ||||
2071 | if (DL) { | ||||
2072 | auto DLI = DL->begin(); | ||||
2073 | auto ADI = ActualDefs.begin(); | ||||
2074 | while (DLI != DL->end() && ADI != ActualDefs.end()) { | ||||
2075 | assert(&*DLI == *ADI && "Not the same defs in the same order")((&*DLI == *ADI && "Not the same defs in the same order" ) ? static_cast<void> (0) : __assert_fail ("&*DLI == *ADI && \"Not the same defs in the same order\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2075, __PRETTY_FUNCTION__)); | ||||
2076 | ++DLI; | ||||
2077 | ++ADI; | ||||
2078 | } | ||||
2079 | } | ||||
2080 | ActualDefs.clear(); | ||||
2081 | } | ||||
2082 | #endif | ||||
2083 | } | ||||
2084 | |||||
2085 | /// Verify the def-use lists in MemorySSA, by verifying that \p Use | ||||
2086 | /// appears in the use list of \p Def. | ||||
2087 | void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const { | ||||
2088 | #ifndef NDEBUG | ||||
2089 | // The live on entry use may cause us to get a NULL def here | ||||
2090 | if (!Def) | ||||
2091 | assert(isLiveOnEntryDef(Use) &&((isLiveOnEntryDef(Use) && "Null def but use not point to live on entry def" ) ? static_cast<void> (0) : __assert_fail ("isLiveOnEntryDef(Use) && \"Null def but use not point to live on entry def\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2092, __PRETTY_FUNCTION__)) | ||||
2092 | "Null def but use not point to live on entry def")((isLiveOnEntryDef(Use) && "Null def but use not point to live on entry def" ) ? static_cast<void> (0) : __assert_fail ("isLiveOnEntryDef(Use) && \"Null def but use not point to live on entry def\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2092, __PRETTY_FUNCTION__)); | ||||
2093 | else | ||||
2094 | assert(is_contained(Def->users(), Use) &&((is_contained(Def->users(), Use) && "Did not find use in def's use list" ) ? static_cast<void> (0) : __assert_fail ("is_contained(Def->users(), Use) && \"Did not find use in def's use list\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2095, __PRETTY_FUNCTION__)) | ||||
2095 | "Did not find use in def's use list")((is_contained(Def->users(), Use) && "Did not find use in def's use list" ) ? static_cast<void> (0) : __assert_fail ("is_contained(Def->users(), Use) && \"Did not find use in def's use list\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2095, __PRETTY_FUNCTION__)); | ||||
2096 | #endif | ||||
2097 | } | ||||
2098 | |||||
2099 | /// Perform a local numbering on blocks so that instruction ordering can be | ||||
2100 | /// determined in constant time. | ||||
2101 | /// TODO: We currently just number in order. If we numbered by N, we could | ||||
2102 | /// allow at least N-1 sequences of insertBefore or insertAfter (and at least | ||||
2103 | /// log2(N) sequences of mixed before and after) without needing to invalidate | ||||
2104 | /// the numbering. | ||||
2105 | void MemorySSA::renumberBlock(const BasicBlock *B) const { | ||||
2106 | // The pre-increment ensures the numbers really start at 1. | ||||
2107 | unsigned long CurrentNumber = 0; | ||||
2108 | const AccessList *AL = getBlockAccesses(B); | ||||
2109 | assert(AL != nullptr && "Asking to renumber an empty block")((AL != nullptr && "Asking to renumber an empty block" ) ? static_cast<void> (0) : __assert_fail ("AL != nullptr && \"Asking to renumber an empty block\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2109, __PRETTY_FUNCTION__)); | ||||
2110 | for (const auto &I : *AL) | ||||
2111 | BlockNumbering[&I] = ++CurrentNumber; | ||||
2112 | BlockNumberingValid.insert(B); | ||||
2113 | } | ||||
2114 | |||||
2115 | /// Determine, for two memory accesses in the same block, | ||||
2116 | /// whether \p Dominator dominates \p Dominatee. | ||||
2117 | /// \returns True if \p Dominator dominates \p Dominatee. | ||||
2118 | bool MemorySSA::locallyDominates(const MemoryAccess *Dominator, | ||||
2119 | const MemoryAccess *Dominatee) const { | ||||
2120 | const BasicBlock *DominatorBlock = Dominator->getBlock(); | ||||
2121 | |||||
2122 | assert((DominatorBlock == Dominatee->getBlock()) &&(((DominatorBlock == Dominatee->getBlock()) && "Asking for local domination when accesses are in different blocks!" ) ? static_cast<void> (0) : __assert_fail ("(DominatorBlock == Dominatee->getBlock()) && \"Asking for local domination when accesses are in different blocks!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2123, __PRETTY_FUNCTION__)) | ||||
2123 | "Asking for local domination when accesses are in different blocks!")(((DominatorBlock == Dominatee->getBlock()) && "Asking for local domination when accesses are in different blocks!" ) ? static_cast<void> (0) : __assert_fail ("(DominatorBlock == Dominatee->getBlock()) && \"Asking for local domination when accesses are in different blocks!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2123, __PRETTY_FUNCTION__)); | ||||
2124 | // A node dominates itself. | ||||
2125 | if (Dominatee == Dominator) | ||||
2126 | return true; | ||||
2127 | |||||
2128 | // When Dominatee is defined on function entry, it is not dominated by another | ||||
2129 | // memory access. | ||||
2130 | if (isLiveOnEntryDef(Dominatee)) | ||||
2131 | return false; | ||||
2132 | |||||
2133 | // When Dominator is defined on function entry, it dominates the other memory | ||||
2134 | // access. | ||||
2135 | if (isLiveOnEntryDef(Dominator)) | ||||
2136 | return true; | ||||
2137 | |||||
2138 | if (!BlockNumberingValid.count(DominatorBlock)) | ||||
2139 | renumberBlock(DominatorBlock); | ||||
2140 | |||||
2141 | unsigned long DominatorNum = BlockNumbering.lookup(Dominator); | ||||
2142 | // All numbers start with 1 | ||||
2143 | assert(DominatorNum != 0 && "Block was not numbered properly")((DominatorNum != 0 && "Block was not numbered properly" ) ? static_cast<void> (0) : __assert_fail ("DominatorNum != 0 && \"Block was not numbered properly\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2143, __PRETTY_FUNCTION__)); | ||||
2144 | unsigned long DominateeNum = BlockNumbering.lookup(Dominatee); | ||||
2145 | assert(DominateeNum != 0 && "Block was not numbered properly")((DominateeNum != 0 && "Block was not numbered properly" ) ? static_cast<void> (0) : __assert_fail ("DominateeNum != 0 && \"Block was not numbered properly\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2145, __PRETTY_FUNCTION__)); | ||||
2146 | return DominatorNum < DominateeNum; | ||||
2147 | } | ||||
2148 | |||||
2149 | bool MemorySSA::dominates(const MemoryAccess *Dominator, | ||||
2150 | const MemoryAccess *Dominatee) const { | ||||
2151 | if (Dominator == Dominatee) | ||||
2152 | return true; | ||||
2153 | |||||
2154 | if (isLiveOnEntryDef(Dominatee)) | ||||
2155 | return false; | ||||
2156 | |||||
2157 | if (Dominator->getBlock() != Dominatee->getBlock()) | ||||
2158 | return DT->dominates(Dominator->getBlock(), Dominatee->getBlock()); | ||||
2159 | return locallyDominates(Dominator, Dominatee); | ||||
2160 | } | ||||
2161 | |||||
2162 | bool MemorySSA::dominates(const MemoryAccess *Dominator, | ||||
2163 | const Use &Dominatee) const { | ||||
2164 | if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) { | ||||
2165 | BasicBlock *UseBB = MP->getIncomingBlock(Dominatee); | ||||
2166 | // The def must dominate the incoming block of the phi. | ||||
2167 | if (UseBB != Dominator->getBlock()) | ||||
2168 | return DT->dominates(Dominator->getBlock(), UseBB); | ||||
2169 | // If the UseBB and the DefBB are the same, compare locally. | ||||
2170 | return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee)); | ||||
2171 | } | ||||
2172 | // If it's not a PHI node use, the normal dominates can already handle it. | ||||
2173 | return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser())); | ||||
2174 | } | ||||
2175 | |||||
2176 | const static char LiveOnEntryStr[] = "liveOnEntry"; | ||||
2177 | |||||
2178 | void MemoryAccess::print(raw_ostream &OS) const { | ||||
2179 | switch (getValueID()) { | ||||
2180 | case MemoryPhiVal: return static_cast<const MemoryPhi *>(this)->print(OS); | ||||
2181 | case MemoryDefVal: return static_cast<const MemoryDef *>(this)->print(OS); | ||||
2182 | case MemoryUseVal: return static_cast<const MemoryUse *>(this)->print(OS); | ||||
2183 | } | ||||
2184 | llvm_unreachable("invalid value id")::llvm::llvm_unreachable_internal("invalid value id", "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2184); | ||||
2185 | } | ||||
2186 | |||||
2187 | void MemoryDef::print(raw_ostream &OS) const { | ||||
2188 | MemoryAccess *UO = getDefiningAccess(); | ||||
2189 | |||||
2190 | auto printID = [&OS](MemoryAccess *A) { | ||||
2191 | if (A && A->getID()) | ||||
2192 | OS << A->getID(); | ||||
2193 | else | ||||
2194 | OS << LiveOnEntryStr; | ||||
2195 | }; | ||||
2196 | |||||
2197 | OS << getID() << " = MemoryDef("; | ||||
2198 | printID(UO); | ||||
2199 | OS << ")"; | ||||
2200 | |||||
2201 | if (isOptimized()) { | ||||
2202 | OS << "->"; | ||||
2203 | printID(getOptimized()); | ||||
2204 | |||||
2205 | if (Optional<AliasResult> AR = getOptimizedAccessType()) | ||||
2206 | OS << " " << *AR; | ||||
2207 | } | ||||
2208 | } | ||||
2209 | |||||
2210 | void MemoryPhi::print(raw_ostream &OS) const { | ||||
2211 | bool First = true; | ||||
2212 | OS << getID() << " = MemoryPhi("; | ||||
2213 | for (const auto &Op : operands()) { | ||||
2214 | BasicBlock *BB = getIncomingBlock(Op); | ||||
2215 | MemoryAccess *MA = cast<MemoryAccess>(Op); | ||||
2216 | if (!First) | ||||
2217 | OS << ','; | ||||
2218 | else | ||||
2219 | First = false; | ||||
2220 | |||||
2221 | OS << '{'; | ||||
2222 | if (BB->hasName()) | ||||
2223 | OS << BB->getName(); | ||||
2224 | else | ||||
2225 | BB->printAsOperand(OS, false); | ||||
2226 | OS << ','; | ||||
2227 | if (unsigned ID = MA->getID()) | ||||
2228 | OS << ID; | ||||
2229 | else | ||||
2230 | OS << LiveOnEntryStr; | ||||
2231 | OS << '}'; | ||||
2232 | } | ||||
2233 | OS << ')'; | ||||
2234 | } | ||||
2235 | |||||
2236 | void MemoryUse::print(raw_ostream &OS) const { | ||||
2237 | MemoryAccess *UO = getDefiningAccess(); | ||||
2238 | OS << "MemoryUse("; | ||||
2239 | if (UO && UO->getID()) | ||||
2240 | OS << UO->getID(); | ||||
2241 | else | ||||
2242 | OS << LiveOnEntryStr; | ||||
2243 | OS << ')'; | ||||
2244 | |||||
2245 | if (Optional<AliasResult> AR = getOptimizedAccessType()) | ||||
2246 | OS << " " << *AR; | ||||
2247 | } | ||||
2248 | |||||
2249 | void MemoryAccess::dump() const { | ||||
2250 | // Cannot completely remove virtual function even in release mode. | ||||
2251 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) | ||||
2252 | print(dbgs()); | ||||
2253 | dbgs() << "\n"; | ||||
2254 | #endif | ||||
2255 | } | ||||
2256 | |||||
2257 | char MemorySSAPrinterLegacyPass::ID = 0; | ||||
2258 | |||||
2259 | MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) { | ||||
2260 | initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry()); | ||||
2261 | } | ||||
2262 | |||||
2263 | void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const { | ||||
2264 | AU.setPreservesAll(); | ||||
2265 | AU.addRequired<MemorySSAWrapperPass>(); | ||||
2266 | } | ||||
2267 | |||||
2268 | class DOTFuncMSSAInfo { | ||||
2269 | private: | ||||
2270 | const Function &F; | ||||
2271 | MemorySSAAnnotatedWriter MSSAWriter; | ||||
2272 | |||||
2273 | public: | ||||
2274 | DOTFuncMSSAInfo(const Function &F, MemorySSA &MSSA) | ||||
2275 | : F(F), MSSAWriter(&MSSA) {} | ||||
2276 | |||||
2277 | const Function *getFunction() { return &F; } | ||||
2278 | MemorySSAAnnotatedWriter &getWriter() { return MSSAWriter; } | ||||
2279 | }; | ||||
2280 | |||||
2281 | namespace llvm { | ||||
2282 | |||||
2283 | template <> | ||||
2284 | struct GraphTraits<DOTFuncMSSAInfo *> : public GraphTraits<const BasicBlock *> { | ||||
2285 | static NodeRef getEntryNode(DOTFuncMSSAInfo *CFGInfo) { | ||||
2286 | return &(CFGInfo->getFunction()->getEntryBlock()); | ||||
2287 | } | ||||
2288 | |||||
2289 | // nodes_iterator/begin/end - Allow iteration over all nodes in the graph | ||||
2290 | using nodes_iterator = pointer_iterator<Function::const_iterator>; | ||||
2291 | |||||
2292 | static nodes_iterator nodes_begin(DOTFuncMSSAInfo *CFGInfo) { | ||||
2293 | return nodes_iterator(CFGInfo->getFunction()->begin()); | ||||
2294 | } | ||||
2295 | |||||
2296 | static nodes_iterator nodes_end(DOTFuncMSSAInfo *CFGInfo) { | ||||
2297 | return nodes_iterator(CFGInfo->getFunction()->end()); | ||||
2298 | } | ||||
2299 | |||||
2300 | static size_t size(DOTFuncMSSAInfo *CFGInfo) { | ||||
2301 | return CFGInfo->getFunction()->size(); | ||||
2302 | } | ||||
2303 | }; | ||||
2304 | |||||
2305 | template <> | ||||
2306 | struct DOTGraphTraits<DOTFuncMSSAInfo *> : public DefaultDOTGraphTraits { | ||||
2307 | |||||
2308 | DOTGraphTraits(bool IsSimple = false) : DefaultDOTGraphTraits(IsSimple) {} | ||||
2309 | |||||
2310 | static std::string getGraphName(DOTFuncMSSAInfo *CFGInfo) { | ||||
2311 | return "MSSA CFG for '" + CFGInfo->getFunction()->getName().str() + | ||||
2312 | "' function"; | ||||
2313 | } | ||||
2314 | |||||
2315 | std::string getNodeLabel(const BasicBlock *Node, DOTFuncMSSAInfo *CFGInfo) { | ||||
2316 | return DOTGraphTraits<DOTFuncInfo *>::getCompleteNodeLabel( | ||||
2317 | Node, nullptr, | ||||
2318 | [CFGInfo](raw_string_ostream &OS, const BasicBlock &BB) -> void { | ||||
2319 | BB.print(OS, &CFGInfo->getWriter(), true, true); | ||||
2320 | }, | ||||
2321 | [](std::string &S, unsigned &I, unsigned Idx) -> void { | ||||
2322 | std::string Str = S.substr(I, Idx - I); | ||||
2323 | StringRef SR = Str; | ||||
2324 | if (SR.count(" = MemoryDef(") || SR.count(" = MemoryPhi(") || | ||||
2325 | SR.count("MemoryUse(")) | ||||
2326 | return; | ||||
2327 | DOTGraphTraits<DOTFuncInfo *>::eraseComment(S, I, Idx); | ||||
2328 | }); | ||||
2329 | } | ||||
2330 | |||||
2331 | static std::string getEdgeSourceLabel(const BasicBlock *Node, | ||||
2332 | const_succ_iterator I) { | ||||
2333 | return DOTGraphTraits<DOTFuncInfo *>::getEdgeSourceLabel(Node, I); | ||||
2334 | } | ||||
2335 | |||||
2336 | /// Display the raw branch weights from PGO. | ||||
2337 | std::string getEdgeAttributes(const BasicBlock *Node, const_succ_iterator I, | ||||
2338 | DOTFuncMSSAInfo *CFGInfo) { | ||||
2339 | return ""; | ||||
2340 | } | ||||
2341 | |||||
2342 | std::string getNodeAttributes(const BasicBlock *Node, | ||||
2343 | DOTFuncMSSAInfo *CFGInfo) { | ||||
2344 | return getNodeLabel(Node, CFGInfo).find(';') != std::string::npos | ||||
2345 | ? "style=filled, fillcolor=lightpink" | ||||
2346 | : ""; | ||||
2347 | } | ||||
2348 | }; | ||||
2349 | |||||
2350 | } // namespace llvm | ||||
2351 | |||||
2352 | bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) { | ||||
2353 | auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA(); | ||||
2354 | if (DotCFGMSSA != "") { | ||||
2355 | DOTFuncMSSAInfo CFGInfo(F, MSSA); | ||||
2356 | WriteGraph(&CFGInfo, "", false, "MSSA", DotCFGMSSA); | ||||
2357 | } else | ||||
2358 | MSSA.print(dbgs()); | ||||
2359 | |||||
2360 | if (VerifyMemorySSA) | ||||
2361 | MSSA.verifyMemorySSA(); | ||||
2362 | return false; | ||||
2363 | } | ||||
2364 | |||||
2365 | AnalysisKey MemorySSAAnalysis::Key; | ||||
2366 | |||||
2367 | MemorySSAAnalysis::Result MemorySSAAnalysis::run(Function &F, | ||||
2368 | FunctionAnalysisManager &AM) { | ||||
2369 | auto &DT = AM.getResult<DominatorTreeAnalysis>(F); | ||||
2370 | auto &AA = AM.getResult<AAManager>(F); | ||||
2371 | return MemorySSAAnalysis::Result(std::make_unique<MemorySSA>(F, &AA, &DT)); | ||||
2372 | } | ||||
2373 | |||||
2374 | bool MemorySSAAnalysis::Result::invalidate( | ||||
2375 | Function &F, const PreservedAnalyses &PA, | ||||
2376 | FunctionAnalysisManager::Invalidator &Inv) { | ||||
2377 | auto PAC = PA.getChecker<MemorySSAAnalysis>(); | ||||
2378 | return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || | ||||
2379 | Inv.invalidate<AAManager>(F, PA) || | ||||
2380 | Inv.invalidate<DominatorTreeAnalysis>(F, PA); | ||||
2381 | } | ||||
2382 | |||||
2383 | PreservedAnalyses MemorySSAPrinterPass::run(Function &F, | ||||
2384 | FunctionAnalysisManager &AM) { | ||||
2385 | auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA(); | ||||
2386 | if (DotCFGMSSA != "") { | ||||
2387 | DOTFuncMSSAInfo CFGInfo(F, MSSA); | ||||
2388 | WriteGraph(&CFGInfo, "", false, "MSSA", DotCFGMSSA); | ||||
2389 | } else { | ||||
2390 | OS << "MemorySSA for function: " << F.getName() << "\n"; | ||||
2391 | MSSA.print(OS); | ||||
2392 | } | ||||
2393 | |||||
2394 | return PreservedAnalyses::all(); | ||||
2395 | } | ||||
2396 | |||||
2397 | PreservedAnalyses MemorySSAVerifierPass::run(Function &F, | ||||
2398 | FunctionAnalysisManager &AM) { | ||||
2399 | AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA(); | ||||
2400 | |||||
2401 | return PreservedAnalyses::all(); | ||||
2402 | } | ||||
2403 | |||||
2404 | char MemorySSAWrapperPass::ID = 0; | ||||
2405 | |||||
2406 | MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) { | ||||
2407 | initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry()); | ||||
2408 | } | ||||
2409 | |||||
2410 | void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); } | ||||
2411 | |||||
2412 | void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { | ||||
2413 | AU.setPreservesAll(); | ||||
2414 | AU.addRequiredTransitive<DominatorTreeWrapperPass>(); | ||||
2415 | AU.addRequiredTransitive<AAResultsWrapperPass>(); | ||||
2416 | } | ||||
2417 | |||||
2418 | bool MemorySSAWrapperPass::runOnFunction(Function &F) { | ||||
2419 | auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); | ||||
2420 | auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); | ||||
2421 | MSSA.reset(new MemorySSA(F, &AA, &DT)); | ||||
2422 | return false; | ||||
2423 | } | ||||
2424 | |||||
2425 | void MemorySSAWrapperPass::verifyAnalysis() const { | ||||
2426 | if (VerifyMemorySSA) | ||||
| |||||
2427 | MSSA->verifyMemorySSA(); | ||||
2428 | } | ||||
2429 | |||||
2430 | void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const { | ||||
2431 | MSSA->print(OS); | ||||
2432 | } | ||||
2433 | |||||
2434 | MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {} | ||||
2435 | |||||
2436 | /// Walk the use-def chains starting at \p StartingAccess and find | ||||
2437 | /// the MemoryAccess that actually clobbers Loc. | ||||
2438 | /// | ||||
2439 | /// \returns our clobbering memory access | ||||
2440 | template <typename AliasAnalysisType> | ||||
2441 | MemoryAccess * | ||||
2442 | MemorySSA::ClobberWalkerBase<AliasAnalysisType>::getClobberingMemoryAccessBase( | ||||
2443 | MemoryAccess *StartingAccess, const MemoryLocation &Loc, | ||||
2444 | unsigned &UpwardWalkLimit) { | ||||
2445 | if (isa<MemoryPhi>(StartingAccess)) | ||||
2446 | return StartingAccess; | ||||
2447 | |||||
2448 | auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess); | ||||
2449 | if (MSSA->isLiveOnEntryDef(StartingUseOrDef)) | ||||
2450 | return StartingUseOrDef; | ||||
2451 | |||||
2452 | Instruction *I = StartingUseOrDef->getMemoryInst(); | ||||
2453 | |||||
2454 | // Conservatively, fences are always clobbers, so don't perform the walk if we | ||||
2455 | // hit a fence. | ||||
2456 | if (!isa<CallBase>(I) && I->isFenceLike()) | ||||
2457 | return StartingUseOrDef; | ||||
2458 | |||||
2459 | UpwardsMemoryQuery Q; | ||||
2460 | Q.OriginalAccess = StartingUseOrDef; | ||||
2461 | Q.StartingLoc = Loc; | ||||
2462 | Q.Inst = nullptr; | ||||
2463 | Q.IsCall = false; | ||||
2464 | |||||
2465 | // Unlike the other function, do not walk to the def of a def, because we are | ||||
2466 | // handed something we already believe is the clobbering access. | ||||
2467 | // We never set SkipSelf to true in Q in this method. | ||||
2468 | MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef) | ||||
2469 | ? StartingUseOrDef->getDefiningAccess() | ||||
2470 | : StartingUseOrDef; | ||||
2471 | |||||
2472 | MemoryAccess *Clobber = | ||||
2473 | Walker.findClobber(DefiningAccess, Q, UpwardWalkLimit); | ||||
2474 | LLVM_DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memoryssa")) { dbgs() << "Starting Memory SSA clobber for " << *I << " is "; } } while (false); | ||||
2475 | LLVM_DEBUG(dbgs() << *StartingUseOrDef << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memoryssa")) { dbgs() << *StartingUseOrDef << "\n" ; } } while (false); | ||||
2476 | LLVM_DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memoryssa")) { dbgs() << "Final Memory SSA clobber for " << *I << " is "; } } while (false); | ||||
2477 | LLVM_DEBUG(dbgs() << *Clobber << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memoryssa")) { dbgs() << *Clobber << "\n"; } } while (false); | ||||
2478 | return Clobber; | ||||
2479 | } | ||||
2480 | |||||
2481 | template <typename AliasAnalysisType> | ||||
2482 | MemoryAccess * | ||||
2483 | MemorySSA::ClobberWalkerBase<AliasAnalysisType>::getClobberingMemoryAccessBase( | ||||
2484 | MemoryAccess *MA, unsigned &UpwardWalkLimit, bool SkipSelf) { | ||||
2485 | auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA); | ||||
2486 | // If this is a MemoryPhi, we can't do anything. | ||||
2487 | if (!StartingAccess) | ||||
2488 | return MA; | ||||
2489 | |||||
2490 | bool IsOptimized = false; | ||||
2491 | |||||
2492 | // If this is an already optimized use or def, return the optimized result. | ||||
2493 | // Note: Currently, we store the optimized def result in a separate field, | ||||
2494 | // since we can't use the defining access. | ||||
2495 | if (StartingAccess->isOptimized()) { | ||||
2496 | if (!SkipSelf || !isa<MemoryDef>(StartingAccess)) | ||||
2497 | return StartingAccess->getOptimized(); | ||||
2498 | IsOptimized = true; | ||||
2499 | } | ||||
2500 | |||||
2501 | const Instruction *I = StartingAccess->getMemoryInst(); | ||||
2502 | // We can't sanely do anything with a fence, since they conservatively clobber | ||||
2503 | // all memory, and have no locations to get pointers from to try to | ||||
2504 | // disambiguate. | ||||
2505 | if (!isa<CallBase>(I) && I->isFenceLike()) | ||||
2506 | return StartingAccess; | ||||
2507 | |||||
2508 | UpwardsMemoryQuery Q(I, StartingAccess); | ||||
2509 | |||||
2510 | if (isUseTriviallyOptimizableToLiveOnEntry(*Walker.getAA(), I)) { | ||||
2511 | MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef(); | ||||
2512 | StartingAccess->setOptimized(LiveOnEntry); | ||||
2513 | StartingAccess->setOptimizedAccessType(None); | ||||
2514 | return LiveOnEntry; | ||||
2515 | } | ||||
2516 | |||||
2517 | MemoryAccess *OptimizedAccess; | ||||
2518 | if (!IsOptimized) { | ||||
2519 | // Start with the thing we already think clobbers this location | ||||
2520 | MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess(); | ||||
2521 | |||||
2522 | // At this point, DefiningAccess may be the live on entry def. | ||||
2523 | // If it is, we will not get a better result. | ||||
2524 | if (MSSA->isLiveOnEntryDef(DefiningAccess)) { | ||||
2525 | StartingAccess->setOptimized(DefiningAccess); | ||||
2526 | StartingAccess->setOptimizedAccessType(None); | ||||
2527 | return DefiningAccess; | ||||
2528 | } | ||||
2529 | |||||
2530 | OptimizedAccess = Walker.findClobber(DefiningAccess, Q, UpwardWalkLimit); | ||||
2531 | StartingAccess->setOptimized(OptimizedAccess); | ||||
2532 | if (MSSA->isLiveOnEntryDef(OptimizedAccess)) | ||||
2533 | StartingAccess->setOptimizedAccessType(None); | ||||
2534 | else if (Q.AR == MustAlias) | ||||
2535 | StartingAccess->setOptimizedAccessType(MustAlias); | ||||
2536 | } else | ||||
2537 | OptimizedAccess = StartingAccess->getOptimized(); | ||||
2538 | |||||
2539 | LLVM_DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memoryssa")) { dbgs() << "Starting Memory SSA clobber for " << *I << " is "; } } while (false); | ||||
2540 | LLVM_DEBUG(dbgs() << *StartingAccess << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memoryssa")) { dbgs() << *StartingAccess << "\n" ; } } while (false); | ||||
2541 | LLVM_DEBUG(dbgs() << "Optimized Memory SSA clobber for " << *I << " is ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memoryssa")) { dbgs() << "Optimized Memory SSA clobber for " << *I << " is "; } } while (false); | ||||
2542 | LLVM_DEBUG(dbgs() << *OptimizedAccess << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memoryssa")) { dbgs() << *OptimizedAccess << "\n" ; } } while (false); | ||||
2543 | |||||
2544 | MemoryAccess *Result; | ||||
2545 | if (SkipSelf && isa<MemoryPhi>(OptimizedAccess) && | ||||
2546 | isa<MemoryDef>(StartingAccess) && UpwardWalkLimit) { | ||||
2547 | assert(isa<MemoryDef>(Q.OriginalAccess))((isa<MemoryDef>(Q.OriginalAccess)) ? static_cast<void > (0) : __assert_fail ("isa<MemoryDef>(Q.OriginalAccess)" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/lib/Analysis/MemorySSA.cpp" , 2547, __PRETTY_FUNCTION__)); | ||||
2548 | Q.SkipSelfAccess = true; | ||||
2549 | Result = Walker.findClobber(OptimizedAccess, Q, UpwardWalkLimit); | ||||
2550 | } else | ||||
2551 | Result = OptimizedAccess; | ||||
2552 | |||||
2553 | LLVM_DEBUG(dbgs() << "Result Memory SSA clobber [SkipSelf = " << SkipSelf)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memoryssa")) { dbgs() << "Result Memory SSA clobber [SkipSelf = " << SkipSelf; } } while (false); | ||||
2554 | LLVM_DEBUG(dbgs() << "] for " << *I << " is " << *Result << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("memoryssa")) { dbgs() << "] for " << *I << " is " << *Result << "\n"; } } while (false); | ||||
2555 | |||||
2556 | return Result; | ||||
2557 | } | ||||
2558 | |||||
2559 | MemoryAccess * | ||||
2560 | DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) { | ||||
2561 | if (auto *Use = dyn_cast<MemoryUseOrDef>(MA)) | ||||
2562 | return Use->getDefiningAccess(); | ||||
2563 | return MA; | ||||
2564 | } | ||||
2565 | |||||
2566 | MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess( | ||||
2567 | MemoryAccess *StartingAccess, const MemoryLocation &) { | ||||
2568 | if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess)) | ||||
2569 | return Use->getDefiningAccess(); | ||||
2570 | return StartingAccess; | ||||
2571 | } | ||||
2572 | |||||
2573 | void MemoryPhi::deleteMe(DerivedUser *Self) { | ||||
2574 | delete static_cast<MemoryPhi *>(Self); | ||||
2575 | } | ||||
2576 | |||||
2577 | void MemoryDef::deleteMe(DerivedUser *Self) { | ||||
2578 | delete static_cast<MemoryDef *>(Self); | ||||
2579 | } | ||||
2580 | |||||
2581 | void MemoryUse::deleteMe(DerivedUser *Self) { | ||||
2582 | delete static_cast<MemoryUse *>(Self); | ||||
2583 | } |
1 | //===- MemorySSA.h - Build Memory SSA ---------------------------*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | /// \file |
10 | /// This file exposes an interface to building/using memory SSA to |
11 | /// walk memory instructions using a use/def graph. |
12 | /// |
13 | /// Memory SSA class builds an SSA form that links together memory access |
14 | /// instructions such as loads, stores, atomics, and calls. Additionally, it |
15 | /// does a trivial form of "heap versioning" Every time the memory state changes |
16 | /// in the program, we generate a new heap version. It generates |
17 | /// MemoryDef/Uses/Phis that are overlayed on top of the existing instructions. |
18 | /// |
19 | /// As a trivial example, |
20 | /// define i32 @main() #0 { |
21 | /// entry: |
22 | /// %call = call noalias i8* @_Znwm(i64 4) #2 |
23 | /// %0 = bitcast i8* %call to i32* |
24 | /// %call1 = call noalias i8* @_Znwm(i64 4) #2 |
25 | /// %1 = bitcast i8* %call1 to i32* |
26 | /// store i32 5, i32* %0, align 4 |
27 | /// store i32 7, i32* %1, align 4 |
28 | /// %2 = load i32* %0, align 4 |
29 | /// %3 = load i32* %1, align 4 |
30 | /// %add = add nsw i32 %2, %3 |
31 | /// ret i32 %add |
32 | /// } |
33 | /// |
34 | /// Will become |
35 | /// define i32 @main() #0 { |
36 | /// entry: |
37 | /// ; 1 = MemoryDef(0) |
38 | /// %call = call noalias i8* @_Znwm(i64 4) #3 |
39 | /// %2 = bitcast i8* %call to i32* |
40 | /// ; 2 = MemoryDef(1) |
41 | /// %call1 = call noalias i8* @_Znwm(i64 4) #3 |
42 | /// %4 = bitcast i8* %call1 to i32* |
43 | /// ; 3 = MemoryDef(2) |
44 | /// store i32 5, i32* %2, align 4 |
45 | /// ; 4 = MemoryDef(3) |
46 | /// store i32 7, i32* %4, align 4 |
47 | /// ; MemoryUse(3) |
48 | /// %7 = load i32* %2, align 4 |
49 | /// ; MemoryUse(4) |
50 | /// %8 = load i32* %4, align 4 |
51 | /// %add = add nsw i32 %7, %8 |
52 | /// ret i32 %add |
53 | /// } |
54 | /// |
55 | /// Given this form, all the stores that could ever effect the load at %8 can be |
56 | /// gotten by using the MemoryUse associated with it, and walking from use to |
57 | /// def until you hit the top of the function. |
58 | /// |
59 | /// Each def also has a list of users associated with it, so you can walk from |
60 | /// both def to users, and users to defs. Note that we disambiguate MemoryUses, |
61 | /// but not the RHS of MemoryDefs. You can see this above at %7, which would |
62 | /// otherwise be a MemoryUse(4). Being disambiguated means that for a given |
63 | /// store, all the MemoryUses on its use lists are may-aliases of that store |
64 | /// (but the MemoryDefs on its use list may not be). |
65 | /// |
66 | /// MemoryDefs are not disambiguated because it would require multiple reaching |
67 | /// definitions, which would require multiple phis, and multiple memoryaccesses |
68 | /// per instruction. |
69 | // |
70 | //===----------------------------------------------------------------------===// |
71 | |
72 | #ifndef LLVM_ANALYSIS_MEMORYSSA_H |
73 | #define LLVM_ANALYSIS_MEMORYSSA_H |
74 | |
75 | #include "llvm/ADT/DenseMap.h" |
76 | #include "llvm/ADT/GraphTraits.h" |
77 | #include "llvm/ADT/SmallPtrSet.h" |
78 | #include "llvm/ADT/SmallVector.h" |
79 | #include "llvm/ADT/ilist.h" |
80 | #include "llvm/ADT/ilist_node.h" |
81 | #include "llvm/ADT/iterator.h" |
82 | #include "llvm/ADT/iterator_range.h" |
83 | #include "llvm/ADT/simple_ilist.h" |
84 | #include "llvm/Analysis/AliasAnalysis.h" |
85 | #include "llvm/Analysis/MemoryLocation.h" |
86 | #include "llvm/Analysis/PHITransAddr.h" |
87 | #include "llvm/IR/BasicBlock.h" |
88 | #include "llvm/IR/DerivedUser.h" |
89 | #include "llvm/IR/Dominators.h" |
90 | #include "llvm/IR/Module.h" |
91 | #include "llvm/IR/Operator.h" |
92 | #include "llvm/IR/Type.h" |
93 | #include "llvm/IR/Use.h" |
94 | #include "llvm/IR/User.h" |
95 | #include "llvm/IR/Value.h" |
96 | #include "llvm/IR/ValueHandle.h" |
97 | #include "llvm/Pass.h" |
98 | #include "llvm/Support/Casting.h" |
99 | #include "llvm/Support/CommandLine.h" |
100 | #include <algorithm> |
101 | #include <cassert> |
102 | #include <cstddef> |
103 | #include <iterator> |
104 | #include <memory> |
105 | #include <utility> |
106 | |
107 | namespace llvm { |
108 | |
109 | /// Enables memory ssa as a dependency for loop passes. |
110 | extern cl::opt<bool> EnableMSSALoopDependency; |
111 | |
112 | class Function; |
113 | class Instruction; |
114 | class MemoryAccess; |
115 | class MemorySSAWalker; |
116 | class LLVMContext; |
117 | class raw_ostream; |
118 | |
119 | namespace MSSAHelpers { |
120 | |
121 | struct AllAccessTag {}; |
122 | struct DefsOnlyTag {}; |
123 | |
124 | } // end namespace MSSAHelpers |
125 | |
126 | enum : unsigned { |
127 | // Used to signify what the default invalid ID is for MemoryAccess's |
128 | // getID() |
129 | INVALID_MEMORYACCESS_ID = -1U |
130 | }; |
131 | |
132 | template <class T> class memoryaccess_def_iterator_base; |
133 | using memoryaccess_def_iterator = memoryaccess_def_iterator_base<MemoryAccess>; |
134 | using const_memoryaccess_def_iterator = |
135 | memoryaccess_def_iterator_base<const MemoryAccess>; |
136 | |
137 | // The base for all memory accesses. All memory accesses in a block are |
138 | // linked together using an intrusive list. |
139 | class MemoryAccess |
140 | : public DerivedUser, |
141 | public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>, |
142 | public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>> { |
143 | public: |
144 | using AllAccessType = |
145 | ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>; |
146 | using DefsOnlyType = |
147 | ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>>; |
148 | |
149 | MemoryAccess(const MemoryAccess &) = delete; |
150 | MemoryAccess &operator=(const MemoryAccess &) = delete; |
151 | |
152 | void *operator new(size_t) = delete; |
153 | |
154 | // Methods for support type inquiry through isa, cast, and |
155 | // dyn_cast |
156 | static bool classof(const Value *V) { |
157 | unsigned ID = V->getValueID(); |
158 | return ID == MemoryUseVal || ID == MemoryPhiVal || ID == MemoryDefVal; |
159 | } |
160 | |
161 | BasicBlock *getBlock() const { return Block; } |
162 | |
163 | void print(raw_ostream &OS) const; |
164 | void dump() const; |
165 | |
166 | /// The user iterators for a memory access |
167 | using iterator = user_iterator; |
168 | using const_iterator = const_user_iterator; |
169 | |
170 | /// This iterator walks over all of the defs in a given |
171 | /// MemoryAccess. For MemoryPhi nodes, this walks arguments. For |
172 | /// MemoryUse/MemoryDef, this walks the defining access. |
173 | memoryaccess_def_iterator defs_begin(); |
174 | const_memoryaccess_def_iterator defs_begin() const; |
175 | memoryaccess_def_iterator defs_end(); |
176 | const_memoryaccess_def_iterator defs_end() const; |
177 | |
178 | /// Get the iterators for the all access list and the defs only list |
179 | /// We default to the all access list. |
180 | AllAccessType::self_iterator getIterator() { |
181 | return this->AllAccessType::getIterator(); |
182 | } |
183 | AllAccessType::const_self_iterator getIterator() const { |
184 | return this->AllAccessType::getIterator(); |
185 | } |
186 | AllAccessType::reverse_self_iterator getReverseIterator() { |
187 | return this->AllAccessType::getReverseIterator(); |
188 | } |
189 | AllAccessType::const_reverse_self_iterator getReverseIterator() const { |
190 | return this->AllAccessType::getReverseIterator(); |
191 | } |
192 | DefsOnlyType::self_iterator getDefsIterator() { |
193 | return this->DefsOnlyType::getIterator(); |
194 | } |
195 | DefsOnlyType::const_self_iterator getDefsIterator() const { |
196 | return this->DefsOnlyType::getIterator(); |
197 | } |
198 | DefsOnlyType::reverse_self_iterator getReverseDefsIterator() { |
199 | return this->DefsOnlyType::getReverseIterator(); |
200 | } |
201 | DefsOnlyType::const_reverse_self_iterator getReverseDefsIterator() const { |
202 | return this->DefsOnlyType::getReverseIterator(); |
203 | } |
204 | |
205 | protected: |
206 | friend class MemoryDef; |
207 | friend class MemoryPhi; |
208 | friend class MemorySSA; |
209 | friend class MemoryUse; |
210 | friend class MemoryUseOrDef; |
211 | |
212 | /// Used by MemorySSA to change the block of a MemoryAccess when it is |
213 | /// moved. |
214 | void setBlock(BasicBlock *BB) { Block = BB; } |
215 | |
216 | /// Used for debugging and tracking things about MemoryAccesses. |
217 | /// Guaranteed unique among MemoryAccesses, no guarantees otherwise. |
218 | inline unsigned getID() const; |
219 | |
220 | MemoryAccess(LLVMContext &C, unsigned Vty, DeleteValueTy DeleteValue, |
221 | BasicBlock *BB, unsigned NumOperands) |
222 | : DerivedUser(Type::getVoidTy(C), Vty, nullptr, NumOperands, DeleteValue), |
223 | Block(BB) {} |
224 | |
225 | // Use deleteValue() to delete a generic MemoryAccess. |
226 | ~MemoryAccess() = default; |
227 | |
228 | private: |
229 | BasicBlock *Block; |
230 | }; |
231 | |
232 | template <> |
233 | struct ilist_alloc_traits<MemoryAccess> { |
234 | static void deleteNode(MemoryAccess *MA) { MA->deleteValue(); } |
235 | }; |
236 | |
237 | inline raw_ostream &operator<<(raw_ostream &OS, const MemoryAccess &MA) { |
238 | MA.print(OS); |
239 | return OS; |
240 | } |
241 | |
242 | /// Class that has the common methods + fields of memory uses/defs. It's |
243 | /// a little awkward to have, but there are many cases where we want either a |
244 | /// use or def, and there are many cases where uses are needed (defs aren't |
245 | /// acceptable), and vice-versa. |
246 | /// |
247 | /// This class should never be instantiated directly; make a MemoryUse or |
248 | /// MemoryDef instead. |
249 | class MemoryUseOrDef : public MemoryAccess { |
250 | public: |
251 | void *operator new(size_t) = delete; |
252 | |
253 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess)public: inline MemoryAccess *getOperand(unsigned) const; inline void setOperand(unsigned, MemoryAccess*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const ; protected: template <int> inline Use &Op(); template <int> inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
254 | |
255 | /// Get the instruction that this MemoryUse represents. |
256 | Instruction *getMemoryInst() const { return MemoryInstruction; } |
257 | |
258 | /// Get the access that produces the memory state used by this Use. |
259 | MemoryAccess *getDefiningAccess() const { return getOperand(0); } |
260 | |
261 | static bool classof(const Value *MA) { |
262 | return MA->getValueID() == MemoryUseVal || MA->getValueID() == MemoryDefVal; |
263 | } |
264 | |
265 | // Sadly, these have to be public because they are needed in some of the |
266 | // iterators. |
267 | inline bool isOptimized() const; |
268 | inline MemoryAccess *getOptimized() const; |
269 | inline void setOptimized(MemoryAccess *); |
270 | |
271 | // Retrieve AliasResult type of the optimized access. Ideally this would be |
272 | // returned by the caching walker and may go away in the future. |
273 | Optional<AliasResult> getOptimizedAccessType() const { |
274 | return isOptimized() ? OptimizedAccessAlias : None; |
275 | } |
276 | |
277 | /// Reset the ID of what this MemoryUse was optimized to, causing it to |
278 | /// be rewalked by the walker if necessary. |
279 | /// This really should only be called by tests. |
280 | inline void resetOptimized(); |
281 | |
282 | protected: |
283 | friend class MemorySSA; |
284 | friend class MemorySSAUpdater; |
285 | |
286 | MemoryUseOrDef(LLVMContext &C, MemoryAccess *DMA, unsigned Vty, |
287 | DeleteValueTy DeleteValue, Instruction *MI, BasicBlock *BB, |
288 | unsigned NumOperands) |
289 | : MemoryAccess(C, Vty, DeleteValue, BB, NumOperands), |
290 | MemoryInstruction(MI), OptimizedAccessAlias(MayAlias) { |
291 | setDefiningAccess(DMA); |
292 | } |
293 | |
294 | // Use deleteValue() to delete a generic MemoryUseOrDef. |
295 | ~MemoryUseOrDef() = default; |
296 | |
297 | void setOptimizedAccessType(Optional<AliasResult> AR) { |
298 | OptimizedAccessAlias = AR; |
299 | } |
300 | |
301 | void setDefiningAccess(MemoryAccess *DMA, bool Optimized = false, |
302 | Optional<AliasResult> AR = MayAlias) { |
303 | if (!Optimized) { |
304 | setOperand(0, DMA); |
305 | return; |
306 | } |
307 | setOptimized(DMA); |
308 | setOptimizedAccessType(AR); |
309 | } |
310 | |
311 | private: |
312 | Instruction *MemoryInstruction; |
313 | Optional<AliasResult> OptimizedAccessAlias; |
314 | }; |
315 | |
316 | /// Represents read-only accesses to memory |
317 | /// |
318 | /// In particular, the set of Instructions that will be represented by |
319 | /// MemoryUse's is exactly the set of Instructions for which |
320 | /// AliasAnalysis::getModRefInfo returns "Ref". |
321 | class MemoryUse final : public MemoryUseOrDef { |
322 | public: |
323 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess)public: inline MemoryAccess *getOperand(unsigned) const; inline void setOperand(unsigned, MemoryAccess*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const ; protected: template <int> inline Use &Op(); template <int> inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
324 | |
325 | MemoryUse(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB) |
326 | : MemoryUseOrDef(C, DMA, MemoryUseVal, deleteMe, MI, BB, |
327 | /*NumOperands=*/1) {} |
328 | |
329 | // allocate space for exactly one operand |
330 | void *operator new(size_t s) { return User::operator new(s, 1); } |
331 | |
332 | static bool classof(const Value *MA) { |
333 | return MA->getValueID() == MemoryUseVal; |
334 | } |
335 | |
336 | void print(raw_ostream &OS) const; |
337 | |
338 | void setOptimized(MemoryAccess *DMA) { |
339 | OptimizedID = DMA->getID(); |
340 | setOperand(0, DMA); |
341 | } |
342 | |
343 | bool isOptimized() const { |
344 | return getDefiningAccess() && OptimizedID == getDefiningAccess()->getID(); |
345 | } |
346 | |
347 | MemoryAccess *getOptimized() const { |
348 | return getDefiningAccess(); |
349 | } |
350 | |
351 | void resetOptimized() { |
352 | OptimizedID = INVALID_MEMORYACCESS_ID; |
353 | } |
354 | |
355 | protected: |
356 | friend class MemorySSA; |
357 | |
358 | private: |
359 | static void deleteMe(DerivedUser *Self); |
360 | |
361 | unsigned OptimizedID = INVALID_MEMORYACCESS_ID; |
362 | }; |
363 | |
364 | template <> |
365 | struct OperandTraits<MemoryUse> : public FixedNumOperandTraits<MemoryUse, 1> {}; |
366 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryUse, MemoryAccess)MemoryUse::op_iterator MemoryUse::op_begin() { return OperandTraits <MemoryUse>::op_begin(this); } MemoryUse::const_op_iterator MemoryUse::op_begin() const { return OperandTraits<MemoryUse >::op_begin(const_cast<MemoryUse*>(this)); } MemoryUse ::op_iterator MemoryUse::op_end() { return OperandTraits<MemoryUse >::op_end(this); } MemoryUse::const_op_iterator MemoryUse:: op_end() const { return OperandTraits<MemoryUse>::op_end (const_cast<MemoryUse*>(this)); } MemoryAccess *MemoryUse ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<MemoryUse>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<MemoryUse>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 366, __PRETTY_FUNCTION__)); return cast_or_null<MemoryAccess >( OperandTraits<MemoryUse>::op_begin(const_cast< MemoryUse*>(this))[i_nocapture].get()); } void MemoryUse:: setOperand(unsigned i_nocapture, MemoryAccess *Val_nocapture) { ((i_nocapture < OperandTraits<MemoryUse>::operands (this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<MemoryUse>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 366, __PRETTY_FUNCTION__)); OperandTraits<MemoryUse>:: op_begin(this)[i_nocapture] = Val_nocapture; } unsigned MemoryUse ::getNumOperands() const { return OperandTraits<MemoryUse> ::operands(this); } template <int Idx_nocapture> Use & MemoryUse::Op() { return this->OpFrom<Idx_nocapture> (this); } template <int Idx_nocapture> const Use &MemoryUse ::Op() const { return this->OpFrom<Idx_nocapture>(this ); } |
367 | |
368 | /// Represents a read-write access to memory, whether it is a must-alias, |
369 | /// or a may-alias. |
370 | /// |
371 | /// In particular, the set of Instructions that will be represented by |
372 | /// MemoryDef's is exactly the set of Instructions for which |
373 | /// AliasAnalysis::getModRefInfo returns "Mod" or "ModRef". |
374 | /// Note that, in order to provide def-def chains, all defs also have a use |
375 | /// associated with them. This use points to the nearest reaching |
376 | /// MemoryDef/MemoryPhi. |
377 | class MemoryDef final : public MemoryUseOrDef { |
378 | public: |
379 | friend class MemorySSA; |
380 | |
381 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess)public: inline MemoryAccess *getOperand(unsigned) const; inline void setOperand(unsigned, MemoryAccess*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const ; protected: template <int> inline Use &Op(); template <int> inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
382 | |
383 | MemoryDef(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB, |
384 | unsigned Ver) |
385 | : MemoryUseOrDef(C, DMA, MemoryDefVal, deleteMe, MI, BB, |
386 | /*NumOperands=*/2), |
387 | ID(Ver) {} |
388 | |
389 | // allocate space for exactly two operands |
390 | void *operator new(size_t s) { return User::operator new(s, 2); } |
391 | |
392 | static bool classof(const Value *MA) { |
393 | return MA->getValueID() == MemoryDefVal; |
394 | } |
395 | |
396 | void setOptimized(MemoryAccess *MA) { |
397 | setOperand(1, MA); |
398 | OptimizedID = MA->getID(); |
399 | } |
400 | |
401 | MemoryAccess *getOptimized() const { |
402 | return cast_or_null<MemoryAccess>(getOperand(1)); |
403 | } |
404 | |
405 | bool isOptimized() const { |
406 | return getOptimized() && OptimizedID == getOptimized()->getID(); |
407 | } |
408 | |
409 | void resetOptimized() { |
410 | OptimizedID = INVALID_MEMORYACCESS_ID; |
411 | setOperand(1, nullptr); |
412 | } |
413 | |
414 | void print(raw_ostream &OS) const; |
415 | |
416 | unsigned getID() const { return ID; } |
417 | |
418 | private: |
419 | static void deleteMe(DerivedUser *Self); |
420 | |
421 | const unsigned ID; |
422 | unsigned OptimizedID = INVALID_MEMORYACCESS_ID; |
423 | }; |
424 | |
425 | template <> |
426 | struct OperandTraits<MemoryDef> : public FixedNumOperandTraits<MemoryDef, 2> {}; |
427 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryDef, MemoryAccess)MemoryDef::op_iterator MemoryDef::op_begin() { return OperandTraits <MemoryDef>::op_begin(this); } MemoryDef::const_op_iterator MemoryDef::op_begin() const { return OperandTraits<MemoryDef >::op_begin(const_cast<MemoryDef*>(this)); } MemoryDef ::op_iterator MemoryDef::op_end() { return OperandTraits<MemoryDef >::op_end(this); } MemoryDef::const_op_iterator MemoryDef:: op_end() const { return OperandTraits<MemoryDef>::op_end (const_cast<MemoryDef*>(this)); } MemoryAccess *MemoryDef ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<MemoryDef>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<MemoryDef>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 427, __PRETTY_FUNCTION__)); return cast_or_null<MemoryAccess >( OperandTraits<MemoryDef>::op_begin(const_cast< MemoryDef*>(this))[i_nocapture].get()); } void MemoryDef:: setOperand(unsigned i_nocapture, MemoryAccess *Val_nocapture) { ((i_nocapture < OperandTraits<MemoryDef>::operands (this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<MemoryDef>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 427, __PRETTY_FUNCTION__)); OperandTraits<MemoryDef>:: op_begin(this)[i_nocapture] = Val_nocapture; } unsigned MemoryDef ::getNumOperands() const { return OperandTraits<MemoryDef> ::operands(this); } template <int Idx_nocapture> Use & MemoryDef::Op() { return this->OpFrom<Idx_nocapture> (this); } template <int Idx_nocapture> const Use &MemoryDef ::Op() const { return this->OpFrom<Idx_nocapture>(this ); } |
428 | |
429 | template <> |
430 | struct OperandTraits<MemoryUseOrDef> { |
431 | static Use *op_begin(MemoryUseOrDef *MUD) { |
432 | if (auto *MU = dyn_cast<MemoryUse>(MUD)) |
433 | return OperandTraits<MemoryUse>::op_begin(MU); |
434 | return OperandTraits<MemoryDef>::op_begin(cast<MemoryDef>(MUD)); |
435 | } |
436 | |
437 | static Use *op_end(MemoryUseOrDef *MUD) { |
438 | if (auto *MU = dyn_cast<MemoryUse>(MUD)) |
439 | return OperandTraits<MemoryUse>::op_end(MU); |
440 | return OperandTraits<MemoryDef>::op_end(cast<MemoryDef>(MUD)); |
441 | } |
442 | |
443 | static unsigned operands(const MemoryUseOrDef *MUD) { |
444 | if (const auto *MU = dyn_cast<MemoryUse>(MUD)) |
445 | return OperandTraits<MemoryUse>::operands(MU); |
446 | return OperandTraits<MemoryDef>::operands(cast<MemoryDef>(MUD)); |
447 | } |
448 | }; |
449 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryUseOrDef, MemoryAccess)MemoryUseOrDef::op_iterator MemoryUseOrDef::op_begin() { return OperandTraits<MemoryUseOrDef>::op_begin(this); } MemoryUseOrDef ::const_op_iterator MemoryUseOrDef::op_begin() const { return OperandTraits<MemoryUseOrDef>::op_begin(const_cast< MemoryUseOrDef*>(this)); } MemoryUseOrDef::op_iterator MemoryUseOrDef ::op_end() { return OperandTraits<MemoryUseOrDef>::op_end (this); } MemoryUseOrDef::const_op_iterator MemoryUseOrDef::op_end () const { return OperandTraits<MemoryUseOrDef>::op_end (const_cast<MemoryUseOrDef*>(this)); } MemoryAccess *MemoryUseOrDef ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<MemoryUseOrDef>::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<MemoryUseOrDef>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 449, __PRETTY_FUNCTION__)); return cast_or_null<MemoryAccess >( OperandTraits<MemoryUseOrDef>::op_begin(const_cast <MemoryUseOrDef*>(this))[i_nocapture].get()); } void MemoryUseOrDef ::setOperand(unsigned i_nocapture, MemoryAccess *Val_nocapture ) { ((i_nocapture < OperandTraits<MemoryUseOrDef>::operands (this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<MemoryUseOrDef>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 449, __PRETTY_FUNCTION__)); OperandTraits<MemoryUseOrDef >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned MemoryUseOrDef::getNumOperands() const { return OperandTraits <MemoryUseOrDef>::operands(this); } template <int Idx_nocapture > Use &MemoryUseOrDef::Op() { return this->OpFrom< Idx_nocapture>(this); } template <int Idx_nocapture> const Use &MemoryUseOrDef::Op() const { return this-> OpFrom<Idx_nocapture>(this); } |
450 | |
451 | /// Represents phi nodes for memory accesses. |
452 | /// |
453 | /// These have the same semantic as regular phi nodes, with the exception that |
454 | /// only one phi will ever exist in a given basic block. |
455 | /// Guaranteeing one phi per block means guaranteeing there is only ever one |
456 | /// valid reaching MemoryDef/MemoryPHI along each path to the phi node. |
457 | /// This is ensured by not allowing disambiguation of the RHS of a MemoryDef or |
458 | /// a MemoryPhi's operands. |
459 | /// That is, given |
460 | /// if (a) { |
461 | /// store %a |
462 | /// store %b |
463 | /// } |
464 | /// it *must* be transformed into |
465 | /// if (a) { |
466 | /// 1 = MemoryDef(liveOnEntry) |
467 | /// store %a |
468 | /// 2 = MemoryDef(1) |
469 | /// store %b |
470 | /// } |
471 | /// and *not* |
472 | /// if (a) { |
473 | /// 1 = MemoryDef(liveOnEntry) |
474 | /// store %a |
475 | /// 2 = MemoryDef(liveOnEntry) |
476 | /// store %b |
477 | /// } |
478 | /// even if the two stores do not conflict. Otherwise, both 1 and 2 reach the |
479 | /// end of the branch, and if there are not two phi nodes, one will be |
480 | /// disconnected completely from the SSA graph below that point. |
481 | /// Because MemoryUse's do not generate new definitions, they do not have this |
482 | /// issue. |
483 | class MemoryPhi final : public MemoryAccess { |
484 | // allocate space for exactly zero operands |
485 | void *operator new(size_t s) { return User::operator new(s); } |
486 | |
487 | public: |
488 | /// Provide fast operand accessors |
489 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess)public: inline MemoryAccess *getOperand(unsigned) const; inline void setOperand(unsigned, MemoryAccess*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const ; protected: template <int> inline Use &Op(); template <int> inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
490 | |
491 | MemoryPhi(LLVMContext &C, BasicBlock *BB, unsigned Ver, unsigned NumPreds = 0) |
492 | : MemoryAccess(C, MemoryPhiVal, deleteMe, BB, 0), ID(Ver), |
493 | ReservedSpace(NumPreds) { |
494 | allocHungoffUses(ReservedSpace); |
495 | } |
496 | |
497 | // Block iterator interface. This provides access to the list of incoming |
498 | // basic blocks, which parallels the list of incoming values. |
499 | using block_iterator = BasicBlock **; |
500 | using const_block_iterator = BasicBlock *const *; |
501 | |
502 | block_iterator block_begin() { |
503 | return reinterpret_cast<block_iterator>(op_begin() + ReservedSpace); |
504 | } |
505 | |
506 | const_block_iterator block_begin() const { |
507 | return reinterpret_cast<const_block_iterator>(op_begin() + ReservedSpace); |
508 | } |
509 | |
510 | block_iterator block_end() { return block_begin() + getNumOperands(); } |
511 | |
512 | const_block_iterator block_end() const { |
513 | return block_begin() + getNumOperands(); |
514 | } |
515 | |
516 | iterator_range<block_iterator> blocks() { |
517 | return make_range(block_begin(), block_end()); |
518 | } |
519 | |
520 | iterator_range<const_block_iterator> blocks() const { |
521 | return make_range(block_begin(), block_end()); |
522 | } |
523 | |
524 | op_range incoming_values() { return operands(); } |
525 | |
526 | const_op_range incoming_values() const { return operands(); } |
527 | |
528 | /// Return the number of incoming edges |
529 | unsigned getNumIncomingValues() const { return getNumOperands(); } |
530 | |
531 | /// Return incoming value number x |
532 | MemoryAccess *getIncomingValue(unsigned I) const { return getOperand(I); } |
533 | void setIncomingValue(unsigned I, MemoryAccess *V) { |
534 | assert(V && "PHI node got a null value!")((V && "PHI node got a null value!") ? static_cast< void> (0) : __assert_fail ("V && \"PHI node got a null value!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 534, __PRETTY_FUNCTION__)); |
535 | setOperand(I, V); |
536 | } |
537 | |
538 | static unsigned getOperandNumForIncomingValue(unsigned I) { return I; } |
539 | static unsigned getIncomingValueNumForOperand(unsigned I) { return I; } |
540 | |
541 | /// Return incoming basic block number @p i. |
542 | BasicBlock *getIncomingBlock(unsigned I) const { return block_begin()[I]; } |
543 | |
544 | /// Return incoming basic block corresponding |
545 | /// to an operand of the PHI. |
546 | BasicBlock *getIncomingBlock(const Use &U) const { |
547 | assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?")((this == U.getUser() && "Iterator doesn't point to PHI's Uses?" ) ? static_cast<void> (0) : __assert_fail ("this == U.getUser() && \"Iterator doesn't point to PHI's Uses?\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 547, __PRETTY_FUNCTION__)); |
548 | return getIncomingBlock(unsigned(&U - op_begin())); |
549 | } |
550 | |
551 | /// Return incoming basic block corresponding |
552 | /// to value use iterator. |
553 | BasicBlock *getIncomingBlock(MemoryAccess::const_user_iterator I) const { |
554 | return getIncomingBlock(I.getUse()); |
555 | } |
556 | |
557 | void setIncomingBlock(unsigned I, BasicBlock *BB) { |
558 | assert(BB && "PHI node got a null basic block!")((BB && "PHI node got a null basic block!") ? static_cast <void> (0) : __assert_fail ("BB && \"PHI node got a null basic block!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 558, __PRETTY_FUNCTION__)); |
559 | block_begin()[I] = BB; |
560 | } |
561 | |
562 | /// Add an incoming value to the end of the PHI list |
563 | void addIncoming(MemoryAccess *V, BasicBlock *BB) { |
564 | if (getNumOperands() == ReservedSpace) |
565 | growOperands(); // Get more space! |
566 | // Initialize some new operands. |
567 | setNumHungOffUseOperands(getNumOperands() + 1); |
568 | setIncomingValue(getNumOperands() - 1, V); |
569 | setIncomingBlock(getNumOperands() - 1, BB); |
570 | } |
571 | |
572 | /// Return the first index of the specified basic |
573 | /// block in the value list for this PHI. Returns -1 if no instance. |
574 | int getBasicBlockIndex(const BasicBlock *BB) const { |
575 | for (unsigned I = 0, E = getNumOperands(); I != E; ++I) |
576 | if (block_begin()[I] == BB) |
577 | return I; |
578 | return -1; |
579 | } |
580 | |
581 | MemoryAccess *getIncomingValueForBlock(const BasicBlock *BB) const { |
582 | int Idx = getBasicBlockIndex(BB); |
583 | assert(Idx >= 0 && "Invalid basic block argument!")((Idx >= 0 && "Invalid basic block argument!") ? static_cast <void> (0) : __assert_fail ("Idx >= 0 && \"Invalid basic block argument!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 583, __PRETTY_FUNCTION__)); |
584 | return getIncomingValue(Idx); |
585 | } |
586 | |
587 | // After deleting incoming position I, the order of incoming may be changed. |
588 | void unorderedDeleteIncoming(unsigned I) { |
589 | unsigned E = getNumOperands(); |
590 | assert(I < E && "Cannot remove out of bounds Phi entry.")((I < E && "Cannot remove out of bounds Phi entry." ) ? static_cast<void> (0) : __assert_fail ("I < E && \"Cannot remove out of bounds Phi entry.\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 590, __PRETTY_FUNCTION__)); |
591 | // MemoryPhi must have at least two incoming values, otherwise the MemoryPhi |
592 | // itself should be deleted. |
593 | assert(E >= 2 && "Cannot only remove incoming values in MemoryPhis with "((E >= 2 && "Cannot only remove incoming values in MemoryPhis with " "at least 2 values.") ? static_cast<void> (0) : __assert_fail ("E >= 2 && \"Cannot only remove incoming values in MemoryPhis with \" \"at least 2 values.\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 594, __PRETTY_FUNCTION__)) |
594 | "at least 2 values.")((E >= 2 && "Cannot only remove incoming values in MemoryPhis with " "at least 2 values.") ? static_cast<void> (0) : __assert_fail ("E >= 2 && \"Cannot only remove incoming values in MemoryPhis with \" \"at least 2 values.\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 594, __PRETTY_FUNCTION__)); |
595 | setIncomingValue(I, getIncomingValue(E - 1)); |
596 | setIncomingBlock(I, block_begin()[E - 1]); |
597 | setOperand(E - 1, nullptr); |
598 | block_begin()[E - 1] = nullptr; |
599 | setNumHungOffUseOperands(getNumOperands() - 1); |
600 | } |
601 | |
602 | // After deleting entries that satisfy Pred, remaining entries may have |
603 | // changed order. |
604 | template <typename Fn> void unorderedDeleteIncomingIf(Fn &&Pred) { |
605 | for (unsigned I = 0, E = getNumOperands(); I != E; ++I) |
606 | if (Pred(getIncomingValue(I), getIncomingBlock(I))) { |
607 | unorderedDeleteIncoming(I); |
608 | E = getNumOperands(); |
609 | --I; |
610 | } |
611 | assert(getNumOperands() >= 1 &&((getNumOperands() >= 1 && "Cannot remove all incoming blocks in a MemoryPhi." ) ? static_cast<void> (0) : __assert_fail ("getNumOperands() >= 1 && \"Cannot remove all incoming blocks in a MemoryPhi.\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 612, __PRETTY_FUNCTION__)) |
612 | "Cannot remove all incoming blocks in a MemoryPhi.")((getNumOperands() >= 1 && "Cannot remove all incoming blocks in a MemoryPhi." ) ? static_cast<void> (0) : __assert_fail ("getNumOperands() >= 1 && \"Cannot remove all incoming blocks in a MemoryPhi.\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 612, __PRETTY_FUNCTION__)); |
613 | } |
614 | |
615 | // After deleting incoming block BB, the incoming blocks order may be changed. |
616 | void unorderedDeleteIncomingBlock(const BasicBlock *BB) { |
617 | unorderedDeleteIncomingIf( |
618 | [&](const MemoryAccess *, const BasicBlock *B) { return BB == B; }); |
619 | } |
620 | |
621 | // After deleting incoming memory access MA, the incoming accesses order may |
622 | // be changed. |
623 | void unorderedDeleteIncomingValue(const MemoryAccess *MA) { |
624 | unorderedDeleteIncomingIf( |
625 | [&](const MemoryAccess *M, const BasicBlock *) { return MA == M; }); |
626 | } |
627 | |
628 | static bool classof(const Value *V) { |
629 | return V->getValueID() == MemoryPhiVal; |
630 | } |
631 | |
632 | void print(raw_ostream &OS) const; |
633 | |
634 | unsigned getID() const { return ID; } |
635 | |
636 | protected: |
637 | friend class MemorySSA; |
638 | |
639 | /// this is more complicated than the generic |
640 | /// User::allocHungoffUses, because we have to allocate Uses for the incoming |
641 | /// values and pointers to the incoming blocks, all in one allocation. |
642 | void allocHungoffUses(unsigned N) { |
643 | User::allocHungoffUses(N, /* IsPhi */ true); |
644 | } |
645 | |
646 | private: |
647 | // For debugging only |
648 | const unsigned ID; |
649 | unsigned ReservedSpace; |
650 | |
651 | /// This grows the operand list in response to a push_back style of |
652 | /// operation. This grows the number of ops by 1.5 times. |
653 | void growOperands() { |
654 | unsigned E = getNumOperands(); |
655 | // 2 op PHI nodes are VERY common, so reserve at least enough for that. |
656 | ReservedSpace = std::max(E + E / 2, 2u); |
657 | growHungoffUses(ReservedSpace, /* IsPhi */ true); |
658 | } |
659 | |
660 | static void deleteMe(DerivedUser *Self); |
661 | }; |
662 | |
663 | inline unsigned MemoryAccess::getID() const { |
664 | assert((isa<MemoryDef>(this) || isa<MemoryPhi>(this)) &&(((isa<MemoryDef>(this) || isa<MemoryPhi>(this)) && "only memory defs and phis have ids") ? static_cast<void> (0) : __assert_fail ("(isa<MemoryDef>(this) || isa<MemoryPhi>(this)) && \"only memory defs and phis have ids\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 665, __PRETTY_FUNCTION__)) |
665 | "only memory defs and phis have ids")(((isa<MemoryDef>(this) || isa<MemoryPhi>(this)) && "only memory defs and phis have ids") ? static_cast<void> (0) : __assert_fail ("(isa<MemoryDef>(this) || isa<MemoryPhi>(this)) && \"only memory defs and phis have ids\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 665, __PRETTY_FUNCTION__)); |
666 | if (const auto *MD = dyn_cast<MemoryDef>(this)) |
667 | return MD->getID(); |
668 | return cast<MemoryPhi>(this)->getID(); |
669 | } |
670 | |
671 | inline bool MemoryUseOrDef::isOptimized() const { |
672 | if (const auto *MD = dyn_cast<MemoryDef>(this)) |
673 | return MD->isOptimized(); |
674 | return cast<MemoryUse>(this)->isOptimized(); |
675 | } |
676 | |
677 | inline MemoryAccess *MemoryUseOrDef::getOptimized() const { |
678 | if (const auto *MD = dyn_cast<MemoryDef>(this)) |
679 | return MD->getOptimized(); |
680 | return cast<MemoryUse>(this)->getOptimized(); |
681 | } |
682 | |
683 | inline void MemoryUseOrDef::setOptimized(MemoryAccess *MA) { |
684 | if (auto *MD = dyn_cast<MemoryDef>(this)) |
685 | MD->setOptimized(MA); |
686 | else |
687 | cast<MemoryUse>(this)->setOptimized(MA); |
688 | } |
689 | |
690 | inline void MemoryUseOrDef::resetOptimized() { |
691 | if (auto *MD = dyn_cast<MemoryDef>(this)) |
692 | MD->resetOptimized(); |
693 | else |
694 | cast<MemoryUse>(this)->resetOptimized(); |
695 | } |
696 | |
697 | template <> struct OperandTraits<MemoryPhi> : public HungoffOperandTraits<2> {}; |
698 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryPhi, MemoryAccess)MemoryPhi::op_iterator MemoryPhi::op_begin() { return OperandTraits <MemoryPhi>::op_begin(this); } MemoryPhi::const_op_iterator MemoryPhi::op_begin() const { return OperandTraits<MemoryPhi >::op_begin(const_cast<MemoryPhi*>(this)); } MemoryPhi ::op_iterator MemoryPhi::op_end() { return OperandTraits<MemoryPhi >::op_end(this); } MemoryPhi::const_op_iterator MemoryPhi:: op_end() const { return OperandTraits<MemoryPhi>::op_end (const_cast<MemoryPhi*>(this)); } MemoryAccess *MemoryPhi ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<MemoryPhi>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<MemoryPhi>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 698, __PRETTY_FUNCTION__)); return cast_or_null<MemoryAccess >( OperandTraits<MemoryPhi>::op_begin(const_cast< MemoryPhi*>(this))[i_nocapture].get()); } void MemoryPhi:: setOperand(unsigned i_nocapture, MemoryAccess *Val_nocapture) { ((i_nocapture < OperandTraits<MemoryPhi>::operands (this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<MemoryPhi>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 698, __PRETTY_FUNCTION__)); OperandTraits<MemoryPhi>:: op_begin(this)[i_nocapture] = Val_nocapture; } unsigned MemoryPhi ::getNumOperands() const { return OperandTraits<MemoryPhi> ::operands(this); } template <int Idx_nocapture> Use & MemoryPhi::Op() { return this->OpFrom<Idx_nocapture> (this); } template <int Idx_nocapture> const Use &MemoryPhi ::Op() const { return this->OpFrom<Idx_nocapture>(this ); } |
699 | |
700 | /// Encapsulates MemorySSA, including all data associated with memory |
701 | /// accesses. |
702 | class MemorySSA { |
703 | public: |
704 | MemorySSA(Function &, AliasAnalysis *, DominatorTree *); |
705 | |
706 | // MemorySSA must remain where it's constructed; Walkers it creates store |
707 | // pointers to it. |
708 | MemorySSA(MemorySSA &&) = delete; |
709 | |
710 | ~MemorySSA(); |
711 | |
712 | MemorySSAWalker *getWalker(); |
713 | MemorySSAWalker *getSkipSelfWalker(); |
714 | |
715 | /// Given a memory Mod/Ref'ing instruction, get the MemorySSA |
716 | /// access associated with it. If passed a basic block gets the memory phi |
717 | /// node that exists for that block, if there is one. Otherwise, this will get |
718 | /// a MemoryUseOrDef. |
719 | MemoryUseOrDef *getMemoryAccess(const Instruction *I) const { |
720 | return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I)); |
721 | } |
722 | |
723 | MemoryPhi *getMemoryAccess(const BasicBlock *BB) const { |
724 | return cast_or_null<MemoryPhi>(ValueToMemoryAccess.lookup(cast<Value>(BB))); |
725 | } |
726 | |
727 | DominatorTree &getDomTree() const { return *DT; } |
728 | |
729 | void dump() const; |
730 | void print(raw_ostream &) const; |
731 | |
732 | /// Return true if \p MA represents the live on entry value |
733 | /// |
734 | /// Loads and stores from pointer arguments and other global values may be |
735 | /// defined by memory operations that do not occur in the current function, so |
736 | /// they may be live on entry to the function. MemorySSA represents such |
737 | /// memory state by the live on entry definition, which is guaranteed to occur |
738 | /// before any other memory access in the function. |
739 | inline bool isLiveOnEntryDef(const MemoryAccess *MA) const { |
740 | return MA == LiveOnEntryDef.get(); |
741 | } |
742 | |
743 | inline MemoryAccess *getLiveOnEntryDef() const { |
744 | return LiveOnEntryDef.get(); |
745 | } |
746 | |
747 | // Sadly, iplists, by default, owns and deletes pointers added to the |
748 | // list. It's not currently possible to have two iplists for the same type, |
749 | // where one owns the pointers, and one does not. This is because the traits |
750 | // are per-type, not per-tag. If this ever changes, we should make the |
751 | // DefList an iplist. |
752 | using AccessList = iplist<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>; |
753 | using DefsList = |
754 | simple_ilist<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>>; |
755 | |
756 | /// Return the list of MemoryAccess's for a given basic block. |
757 | /// |
758 | /// This list is not modifiable by the user. |
759 | const AccessList *getBlockAccesses(const BasicBlock *BB) const { |
760 | return getWritableBlockAccesses(BB); |
761 | } |
762 | |
763 | /// Return the list of MemoryDef's and MemoryPhi's for a given basic |
764 | /// block. |
765 | /// |
766 | /// This list is not modifiable by the user. |
767 | const DefsList *getBlockDefs(const BasicBlock *BB) const { |
768 | return getWritableBlockDefs(BB); |
769 | } |
770 | |
771 | /// Given two memory accesses in the same basic block, determine |
772 | /// whether MemoryAccess \p A dominates MemoryAccess \p B. |
773 | bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const; |
774 | |
775 | /// Given two memory accesses in potentially different blocks, |
776 | /// determine whether MemoryAccess \p A dominates MemoryAccess \p B. |
777 | bool dominates(const MemoryAccess *A, const MemoryAccess *B) const; |
778 | |
779 | /// Given a MemoryAccess and a Use, determine whether MemoryAccess \p A |
780 | /// dominates Use \p B. |
781 | bool dominates(const MemoryAccess *A, const Use &B) const; |
782 | |
783 | /// Verify that MemorySSA is self consistent (IE definitions dominate |
784 | /// all uses, uses appear in the right places). This is used by unit tests. |
785 | void verifyMemorySSA() const; |
786 | |
787 | /// Used in various insertion functions to specify whether we are talking |
788 | /// about the beginning or end of a block. |
789 | enum InsertionPlace { Beginning, End, BeforeTerminator }; |
790 | |
791 | protected: |
792 | // Used by Memory SSA annotater, dumpers, and wrapper pass |
793 | friend class MemorySSAAnnotatedWriter; |
794 | friend class MemorySSAPrinterLegacyPass; |
795 | friend class MemorySSAUpdater; |
796 | |
797 | void verifyOrderingDominationAndDefUses(Function &F) const; |
798 | void verifyDominationNumbers(const Function &F) const; |
799 | void verifyPrevDefInPhis(Function &F) const; |
800 | |
801 | // This is used by the use optimizer and updater. |
802 | AccessList *getWritableBlockAccesses(const BasicBlock *BB) const { |
803 | auto It = PerBlockAccesses.find(BB); |
804 | return It == PerBlockAccesses.end() ? nullptr : It->second.get(); |
805 | } |
806 | |
807 | // This is used by the use optimizer and updater. |
808 | DefsList *getWritableBlockDefs(const BasicBlock *BB) const { |
809 | auto It = PerBlockDefs.find(BB); |
810 | return It == PerBlockDefs.end() ? nullptr : It->second.get(); |
811 | } |
812 | |
813 | // These is used by the updater to perform various internal MemorySSA |
814 | // machinsations. They do not always leave the IR in a correct state, and |
815 | // relies on the updater to fixup what it breaks, so it is not public. |
816 | |
817 | void moveTo(MemoryUseOrDef *What, BasicBlock *BB, AccessList::iterator Where); |
818 | void moveTo(MemoryAccess *What, BasicBlock *BB, InsertionPlace Point); |
819 | |
820 | // Rename the dominator tree branch rooted at BB. |
821 | void renamePass(BasicBlock *BB, MemoryAccess *IncomingVal, |
822 | SmallPtrSetImpl<BasicBlock *> &Visited) { |
823 | renamePass(DT->getNode(BB), IncomingVal, Visited, true, true); |
824 | } |
825 | |
826 | void removeFromLookups(MemoryAccess *); |
827 | void removeFromLists(MemoryAccess *, bool ShouldDelete = true); |
828 | void insertIntoListsForBlock(MemoryAccess *, const BasicBlock *, |
829 | InsertionPlace); |
830 | void insertIntoListsBefore(MemoryAccess *, const BasicBlock *, |
831 | AccessList::iterator); |
832 | MemoryUseOrDef *createDefinedAccess(Instruction *, MemoryAccess *, |
833 | const MemoryUseOrDef *Template = nullptr, |
834 | bool CreationMustSucceed = true); |
835 | |
836 | private: |
837 | template <class AliasAnalysisType> class ClobberWalkerBase; |
838 | template <class AliasAnalysisType> class CachingWalker; |
839 | template <class AliasAnalysisType> class SkipSelfWalker; |
840 | class OptimizeUses; |
841 | |
842 | CachingWalker<AliasAnalysis> *getWalkerImpl(); |
843 | void buildMemorySSA(BatchAAResults &BAA); |
844 | |
845 | void prepareForMoveTo(MemoryAccess *, BasicBlock *); |
846 | void verifyUseInDefs(MemoryAccess *, MemoryAccess *) const; |
847 | |
848 | using AccessMap = DenseMap<const BasicBlock *, std::unique_ptr<AccessList>>; |
849 | using DefsMap = DenseMap<const BasicBlock *, std::unique_ptr<DefsList>>; |
850 | |
851 | void markUnreachableAsLiveOnEntry(BasicBlock *BB); |
852 | bool dominatesUse(const MemoryAccess *, const MemoryAccess *) const; |
853 | MemoryPhi *createMemoryPhi(BasicBlock *BB); |
854 | template <typename AliasAnalysisType> |
855 | MemoryUseOrDef *createNewAccess(Instruction *, AliasAnalysisType *, |
856 | const MemoryUseOrDef *Template = nullptr); |
857 | void placePHINodes(const SmallPtrSetImpl<BasicBlock *> &); |
858 | MemoryAccess *renameBlock(BasicBlock *, MemoryAccess *, bool); |
859 | void renameSuccessorPhis(BasicBlock *, MemoryAccess *, bool); |
860 | void renamePass(DomTreeNode *, MemoryAccess *IncomingVal, |
861 | SmallPtrSetImpl<BasicBlock *> &Visited, |
862 | bool SkipVisited = false, bool RenameAllUses = false); |
863 | AccessList *getOrCreateAccessList(const BasicBlock *); |
864 | DefsList *getOrCreateDefsList(const BasicBlock *); |
865 | void renumberBlock(const BasicBlock *) const; |
866 | AliasAnalysis *AA; |
867 | DominatorTree *DT; |
868 | Function &F; |
869 | |
870 | // Memory SSA mappings |
871 | DenseMap<const Value *, MemoryAccess *> ValueToMemoryAccess; |
872 | |
873 | // These two mappings contain the main block to access/def mappings for |
874 | // MemorySSA. The list contained in PerBlockAccesses really owns all the |
875 | // MemoryAccesses. |
876 | // Both maps maintain the invariant that if a block is found in them, the |
877 | // corresponding list is not empty, and if a block is not found in them, the |
878 | // corresponding list is empty. |
879 | AccessMap PerBlockAccesses; |
880 | DefsMap PerBlockDefs; |
881 | std::unique_ptr<MemoryAccess, ValueDeleter> LiveOnEntryDef; |
882 | |
883 | // Domination mappings |
884 | // Note that the numbering is local to a block, even though the map is |
885 | // global. |
886 | mutable SmallPtrSet<const BasicBlock *, 16> BlockNumberingValid; |
887 | mutable DenseMap<const MemoryAccess *, unsigned long> BlockNumbering; |
888 | |
889 | // Memory SSA building info |
890 | std::unique_ptr<ClobberWalkerBase<AliasAnalysis>> WalkerBase; |
891 | std::unique_ptr<CachingWalker<AliasAnalysis>> Walker; |
892 | std::unique_ptr<SkipSelfWalker<AliasAnalysis>> SkipWalker; |
893 | unsigned NextID; |
894 | }; |
895 | |
896 | // Internal MemorySSA utils, for use by MemorySSA classes and walkers |
897 | class MemorySSAUtil { |
898 | protected: |
899 | friend class GVNHoist; |
900 | friend class MemorySSAWalker; |
901 | |
902 | // This function should not be used by new passes. |
903 | static bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU, |
904 | AliasAnalysis &AA); |
905 | }; |
906 | |
907 | // This pass does eager building and then printing of MemorySSA. It is used by |
908 | // the tests to be able to build, dump, and verify Memory SSA. |
909 | class MemorySSAPrinterLegacyPass : public FunctionPass { |
910 | public: |
911 | MemorySSAPrinterLegacyPass(); |
912 | |
913 | bool runOnFunction(Function &) override; |
914 | void getAnalysisUsage(AnalysisUsage &AU) const override; |
915 | |
916 | static char ID; |
917 | }; |
918 | |
919 | /// An analysis that produces \c MemorySSA for a function. |
920 | /// |
921 | class MemorySSAAnalysis : public AnalysisInfoMixin<MemorySSAAnalysis> { |
922 | friend AnalysisInfoMixin<MemorySSAAnalysis>; |
923 | |
924 | static AnalysisKey Key; |
925 | |
926 | public: |
927 | // Wrap MemorySSA result to ensure address stability of internal MemorySSA |
928 | // pointers after construction. Use a wrapper class instead of plain |
929 | // unique_ptr<MemorySSA> to avoid build breakage on MSVC. |
930 | struct Result { |
931 | Result(std::unique_ptr<MemorySSA> &&MSSA) : MSSA(std::move(MSSA)) {} |
932 | |
933 | MemorySSA &getMSSA() { return *MSSA.get(); } |
934 | |
935 | std::unique_ptr<MemorySSA> MSSA; |
936 | |
937 | bool invalidate(Function &F, const PreservedAnalyses &PA, |
938 | FunctionAnalysisManager::Invalidator &Inv); |
939 | }; |
940 | |
941 | Result run(Function &F, FunctionAnalysisManager &AM); |
942 | }; |
943 | |
944 | /// Printer pass for \c MemorySSA. |
945 | class MemorySSAPrinterPass : public PassInfoMixin<MemorySSAPrinterPass> { |
946 | raw_ostream &OS; |
947 | |
948 | public: |
949 | explicit MemorySSAPrinterPass(raw_ostream &OS) : OS(OS) {} |
950 | |
951 | PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM); |
952 | }; |
953 | |
954 | /// Verifier pass for \c MemorySSA. |
955 | struct MemorySSAVerifierPass : PassInfoMixin<MemorySSAVerifierPass> { |
956 | PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM); |
957 | }; |
958 | |
959 | /// Legacy analysis pass which computes \c MemorySSA. |
960 | class MemorySSAWrapperPass : public FunctionPass { |
961 | public: |
962 | MemorySSAWrapperPass(); |
963 | |
964 | static char ID; |
965 | |
966 | bool runOnFunction(Function &) override; |
967 | void releaseMemory() override; |
968 | MemorySSA &getMSSA() { return *MSSA; } |
969 | const MemorySSA &getMSSA() const { return *MSSA; } |
970 | |
971 | void getAnalysisUsage(AnalysisUsage &AU) const override; |
972 | |
973 | void verifyAnalysis() const override; |
974 | void print(raw_ostream &OS, const Module *M = nullptr) const override; |
975 | |
976 | private: |
977 | std::unique_ptr<MemorySSA> MSSA; |
978 | }; |
979 | |
980 | /// This is the generic walker interface for walkers of MemorySSA. |
981 | /// Walkers are used to be able to further disambiguate the def-use chains |
982 | /// MemorySSA gives you, or otherwise produce better info than MemorySSA gives |
983 | /// you. |
984 | /// In particular, while the def-use chains provide basic information, and are |
985 | /// guaranteed to give, for example, the nearest may-aliasing MemoryDef for a |
986 | /// MemoryUse as AliasAnalysis considers it, a user mant want better or other |
987 | /// information. In particular, they may want to use SCEV info to further |
988 | /// disambiguate memory accesses, or they may want the nearest dominating |
989 | /// may-aliasing MemoryDef for a call or a store. This API enables a |
990 | /// standardized interface to getting and using that info. |
991 | class MemorySSAWalker { |
992 | public: |
993 | MemorySSAWalker(MemorySSA *); |
994 | virtual ~MemorySSAWalker() = default; |
995 | |
996 | using MemoryAccessSet = SmallVector<MemoryAccess *, 8>; |
997 | |
998 | /// Given a memory Mod/Ref/ModRef'ing instruction, calling this |
999 | /// will give you the nearest dominating MemoryAccess that Mod's the location |
1000 | /// the instruction accesses (by skipping any def which AA can prove does not |
1001 | /// alias the location(s) accessed by the instruction given). |
1002 | /// |
1003 | /// Note that this will return a single access, and it must dominate the |
1004 | /// Instruction, so if an operand of a MemoryPhi node Mod's the instruction, |
1005 | /// this will return the MemoryPhi, not the operand. This means that |
1006 | /// given: |
1007 | /// if (a) { |
1008 | /// 1 = MemoryDef(liveOnEntry) |
1009 | /// store %a |
1010 | /// } else { |
1011 | /// 2 = MemoryDef(liveOnEntry) |
1012 | /// store %b |
1013 | /// } |
1014 | /// 3 = MemoryPhi(2, 1) |
1015 | /// MemoryUse(3) |
1016 | /// load %a |
1017 | /// |
1018 | /// calling this API on load(%a) will return the MemoryPhi, not the MemoryDef |
1019 | /// in the if (a) branch. |
1020 | MemoryAccess *getClobberingMemoryAccess(const Instruction *I) { |
1021 | MemoryAccess *MA = MSSA->getMemoryAccess(I); |
1022 | assert(MA && "Handed an instruction that MemorySSA doesn't recognize?")((MA && "Handed an instruction that MemorySSA doesn't recognize?" ) ? static_cast<void> (0) : __assert_fail ("MA && \"Handed an instruction that MemorySSA doesn't recognize?\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 1022, __PRETTY_FUNCTION__)); |
1023 | return getClobberingMemoryAccess(MA); |
1024 | } |
1025 | |
1026 | /// Does the same thing as getClobberingMemoryAccess(const Instruction *I), |
1027 | /// but takes a MemoryAccess instead of an Instruction. |
1028 | virtual MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) = 0; |
1029 | |
1030 | /// Given a potentially clobbering memory access and a new location, |
1031 | /// calling this will give you the nearest dominating clobbering MemoryAccess |
1032 | /// (by skipping non-aliasing def links). |
1033 | /// |
1034 | /// This version of the function is mainly used to disambiguate phi translated |
1035 | /// pointers, where the value of a pointer may have changed from the initial |
1036 | /// memory access. Note that this expects to be handed either a MemoryUse, |
1037 | /// or an already potentially clobbering access. Unlike the above API, if |
1038 | /// given a MemoryDef that clobbers the pointer as the starting access, it |
1039 | /// will return that MemoryDef, whereas the above would return the clobber |
1040 | /// starting from the use side of the memory def. |
1041 | virtual MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, |
1042 | const MemoryLocation &) = 0; |
1043 | |
1044 | /// Given a memory access, invalidate anything this walker knows about |
1045 | /// that access. |
1046 | /// This API is used by walkers that store information to perform basic cache |
1047 | /// invalidation. This will be called by MemorySSA at appropriate times for |
1048 | /// the walker it uses or returns. |
1049 | virtual void invalidateInfo(MemoryAccess *) {} |
1050 | |
1051 | protected: |
1052 | friend class MemorySSA; // For updating MSSA pointer in MemorySSA move |
1053 | // constructor. |
1054 | MemorySSA *MSSA; |
1055 | }; |
1056 | |
1057 | /// A MemorySSAWalker that does no alias queries, or anything else. It |
1058 | /// simply returns the links as they were constructed by the builder. |
1059 | class DoNothingMemorySSAWalker final : public MemorySSAWalker { |
1060 | public: |
1061 | // Keep the overrides below from hiding the Instruction overload of |
1062 | // getClobberingMemoryAccess. |
1063 | using MemorySSAWalker::getClobberingMemoryAccess; |
1064 | |
1065 | MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override; |
1066 | MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, |
1067 | const MemoryLocation &) override; |
1068 | }; |
1069 | |
1070 | using MemoryAccessPair = std::pair<MemoryAccess *, MemoryLocation>; |
1071 | using ConstMemoryAccessPair = std::pair<const MemoryAccess *, MemoryLocation>; |
1072 | |
1073 | /// Iterator base class used to implement const and non-const iterators |
1074 | /// over the defining accesses of a MemoryAccess. |
1075 | template <class T> |
1076 | class memoryaccess_def_iterator_base |
1077 | : public iterator_facade_base<memoryaccess_def_iterator_base<T>, |
1078 | std::forward_iterator_tag, T, ptrdiff_t, T *, |
1079 | T *> { |
1080 | using BaseT = typename memoryaccess_def_iterator_base::iterator_facade_base; |
1081 | |
1082 | public: |
1083 | memoryaccess_def_iterator_base(T *Start) : Access(Start) {} |
1084 | memoryaccess_def_iterator_base() = default; |
1085 | |
1086 | bool operator==(const memoryaccess_def_iterator_base &Other) const { |
1087 | return Access == Other.Access && (!Access || ArgNo == Other.ArgNo); |
1088 | } |
1089 | |
1090 | // This is a bit ugly, but for MemoryPHI's, unlike PHINodes, you can't get the |
1091 | // block from the operand in constant time (In a PHINode, the uselist has |
1092 | // both, so it's just subtraction). We provide it as part of the |
1093 | // iterator to avoid callers having to linear walk to get the block. |
1094 | // If the operation becomes constant time on MemoryPHI's, this bit of |
1095 | // abstraction breaking should be removed. |
1096 | BasicBlock *getPhiArgBlock() const { |
1097 | MemoryPhi *MP = dyn_cast<MemoryPhi>(Access); |
1098 | assert(MP && "Tried to get phi arg block when not iterating over a PHI")((MP && "Tried to get phi arg block when not iterating over a PHI" ) ? static_cast<void> (0) : __assert_fail ("MP && \"Tried to get phi arg block when not iterating over a PHI\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 1098, __PRETTY_FUNCTION__)); |
1099 | return MP->getIncomingBlock(ArgNo); |
1100 | } |
1101 | |
1102 | typename BaseT::iterator::pointer operator*() const { |
1103 | assert(Access && "Tried to access past the end of our iterator")((Access && "Tried to access past the end of our iterator" ) ? static_cast<void> (0) : __assert_fail ("Access && \"Tried to access past the end of our iterator\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 1103, __PRETTY_FUNCTION__)); |
1104 | // Go to the first argument for phis, and the defining access for everything |
1105 | // else. |
1106 | if (const MemoryPhi *MP = dyn_cast<MemoryPhi>(Access)) |
1107 | return MP->getIncomingValue(ArgNo); |
1108 | return cast<MemoryUseOrDef>(Access)->getDefiningAccess(); |
1109 | } |
1110 | |
1111 | using BaseT::operator++; |
1112 | memoryaccess_def_iterator_base &operator++() { |
1113 | assert(Access && "Hit end of iterator")((Access && "Hit end of iterator") ? static_cast<void > (0) : __assert_fail ("Access && \"Hit end of iterator\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 1113, __PRETTY_FUNCTION__)); |
1114 | if (const MemoryPhi *MP = dyn_cast<MemoryPhi>(Access)) { |
1115 | if (++ArgNo >= MP->getNumIncomingValues()) { |
1116 | ArgNo = 0; |
1117 | Access = nullptr; |
1118 | } |
1119 | } else { |
1120 | Access = nullptr; |
1121 | } |
1122 | return *this; |
1123 | } |
1124 | |
1125 | private: |
1126 | T *Access = nullptr; |
1127 | unsigned ArgNo = 0; |
1128 | }; |
1129 | |
1130 | inline memoryaccess_def_iterator MemoryAccess::defs_begin() { |
1131 | return memoryaccess_def_iterator(this); |
1132 | } |
1133 | |
1134 | inline const_memoryaccess_def_iterator MemoryAccess::defs_begin() const { |
1135 | return const_memoryaccess_def_iterator(this); |
1136 | } |
1137 | |
1138 | inline memoryaccess_def_iterator MemoryAccess::defs_end() { |
1139 | return memoryaccess_def_iterator(); |
1140 | } |
1141 | |
1142 | inline const_memoryaccess_def_iterator MemoryAccess::defs_end() const { |
1143 | return const_memoryaccess_def_iterator(); |
1144 | } |
1145 | |
1146 | /// GraphTraits for a MemoryAccess, which walks defs in the normal case, |
1147 | /// and uses in the inverse case. |
1148 | template <> struct GraphTraits<MemoryAccess *> { |
1149 | using NodeRef = MemoryAccess *; |
1150 | using ChildIteratorType = memoryaccess_def_iterator; |
1151 | |
1152 | static NodeRef getEntryNode(NodeRef N) { return N; } |
1153 | static ChildIteratorType child_begin(NodeRef N) { return N->defs_begin(); } |
1154 | static ChildIteratorType child_end(NodeRef N) { return N->defs_end(); } |
1155 | }; |
1156 | |
1157 | template <> struct GraphTraits<Inverse<MemoryAccess *>> { |
1158 | using NodeRef = MemoryAccess *; |
1159 | using ChildIteratorType = MemoryAccess::iterator; |
1160 | |
1161 | static NodeRef getEntryNode(NodeRef N) { return N; } |
1162 | static ChildIteratorType child_begin(NodeRef N) { return N->user_begin(); } |
1163 | static ChildIteratorType child_end(NodeRef N) { return N->user_end(); } |
1164 | }; |
1165 | |
1166 | /// Provide an iterator that walks defs, giving both the memory access, |
1167 | /// and the current pointer location, updating the pointer location as it |
1168 | /// changes due to phi node translation. |
1169 | /// |
1170 | /// This iterator, while somewhat specialized, is what most clients actually |
1171 | /// want when walking upwards through MemorySSA def chains. It takes a pair of |
1172 | /// <MemoryAccess,MemoryLocation>, and walks defs, properly translating the |
1173 | /// memory location through phi nodes for the user. |
1174 | class upward_defs_iterator |
1175 | : public iterator_facade_base<upward_defs_iterator, |
1176 | std::forward_iterator_tag, |
1177 | const MemoryAccessPair> { |
1178 | using BaseT = upward_defs_iterator::iterator_facade_base; |
1179 | |
1180 | public: |
1181 | upward_defs_iterator(const MemoryAccessPair &Info, DominatorTree *DT, |
1182 | bool *PerformedPhiTranslation = nullptr) |
1183 | : DefIterator(Info.first), Location(Info.second), |
1184 | OriginalAccess(Info.first), DT(DT), |
1185 | PerformedPhiTranslation(PerformedPhiTranslation) { |
1186 | CurrentPair.first = nullptr; |
1187 | |
1188 | WalkingPhi = Info.first && isa<MemoryPhi>(Info.first); |
1189 | fillInCurrentPair(); |
1190 | } |
1191 | |
1192 | upward_defs_iterator() { CurrentPair.first = nullptr; } |
1193 | |
1194 | bool operator==(const upward_defs_iterator &Other) const { |
1195 | return DefIterator == Other.DefIterator; |
1196 | } |
1197 | |
1198 | BaseT::iterator::reference operator*() const { |
1199 | assert(DefIterator != OriginalAccess->defs_end() &&((DefIterator != OriginalAccess->defs_end() && "Tried to access past the end of our iterator" ) ? static_cast<void> (0) : __assert_fail ("DefIterator != OriginalAccess->defs_end() && \"Tried to access past the end of our iterator\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 1200, __PRETTY_FUNCTION__)) |
1200 | "Tried to access past the end of our iterator")((DefIterator != OriginalAccess->defs_end() && "Tried to access past the end of our iterator" ) ? static_cast<void> (0) : __assert_fail ("DefIterator != OriginalAccess->defs_end() && \"Tried to access past the end of our iterator\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 1200, __PRETTY_FUNCTION__)); |
1201 | return CurrentPair; |
1202 | } |
1203 | |
1204 | using BaseT::operator++; |
1205 | upward_defs_iterator &operator++() { |
1206 | assert(DefIterator != OriginalAccess->defs_end() &&((DefIterator != OriginalAccess->defs_end() && "Tried to access past the end of the iterator" ) ? static_cast<void> (0) : __assert_fail ("DefIterator != OriginalAccess->defs_end() && \"Tried to access past the end of the iterator\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 1207, __PRETTY_FUNCTION__)) |
1207 | "Tried to access past the end of the iterator")((DefIterator != OriginalAccess->defs_end() && "Tried to access past the end of the iterator" ) ? static_cast<void> (0) : __assert_fail ("DefIterator != OriginalAccess->defs_end() && \"Tried to access past the end of the iterator\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 1207, __PRETTY_FUNCTION__)); |
1208 | ++DefIterator; |
1209 | if (DefIterator != OriginalAccess->defs_end()) |
1210 | fillInCurrentPair(); |
1211 | return *this; |
1212 | } |
1213 | |
1214 | BasicBlock *getPhiArgBlock() const { return DefIterator.getPhiArgBlock(); } |
1215 | |
1216 | private: |
1217 | /// Returns true if \p Ptr is guaranteed to be loop invariant for any possible |
1218 | /// loop. In particular, this guarantees that it only references a single |
1219 | /// MemoryLocation during execution of the containing function. |
1220 | bool IsGuaranteedLoopInvariant(Value *Ptr) const { |
1221 | auto IsGuaranteedLoopInvariantBase = [](Value *Ptr) { |
1222 | Ptr = Ptr->stripPointerCasts(); |
1223 | if (!isa<Instruction>(Ptr)) |
1224 | return true; |
1225 | return isa<AllocaInst>(Ptr); |
1226 | }; |
1227 | |
1228 | Ptr = Ptr->stripPointerCasts(); |
1229 | if (auto *GEP = dyn_cast<GEPOperator>(Ptr)) { |
1230 | return IsGuaranteedLoopInvariantBase(GEP->getPointerOperand()) && |
1231 | GEP->hasAllConstantIndices(); |
1232 | } |
1233 | return IsGuaranteedLoopInvariantBase(Ptr); |
1234 | } |
1235 | |
1236 | void fillInCurrentPair() { |
1237 | CurrentPair.first = *DefIterator; |
1238 | CurrentPair.second = Location; |
1239 | if (WalkingPhi && Location.Ptr) { |
1240 | // Mark size as unknown, if the location is not guaranteed to be |
1241 | // loop-invariant for any possible loop in the function. Setting the size |
1242 | // to unknown guarantees that any memory accesses that access locations |
1243 | // after the pointer are considered as clobbers, which is important to |
1244 | // catch loop carried dependences. |
1245 | if (Location.Ptr && |
1246 | !IsGuaranteedLoopInvariant(const_cast<Value *>(Location.Ptr))) |
1247 | CurrentPair.second = |
1248 | Location.getWithNewSize(LocationSize::beforeOrAfterPointer()); |
1249 | PHITransAddr Translator( |
1250 | const_cast<Value *>(Location.Ptr), |
1251 | OriginalAccess->getBlock()->getModule()->getDataLayout(), nullptr); |
1252 | |
1253 | if (!Translator.PHITranslateValue(OriginalAccess->getBlock(), |
1254 | DefIterator.getPhiArgBlock(), DT, |
1255 | true)) { |
1256 | Value *TransAddr = Translator.getAddr(); |
1257 | if (TransAddr != Location.Ptr) { |
1258 | CurrentPair.second = CurrentPair.second.getWithNewPtr(TransAddr); |
1259 | |
1260 | if (TransAddr && |
1261 | !IsGuaranteedLoopInvariant(const_cast<Value *>(TransAddr))) |
1262 | CurrentPair.second = CurrentPair.second.getWithNewSize( |
1263 | LocationSize::beforeOrAfterPointer()); |
1264 | |
1265 | if (PerformedPhiTranslation) |
1266 | *PerformedPhiTranslation = true; |
1267 | } |
1268 | } |
1269 | } |
1270 | } |
1271 | |
1272 | MemoryAccessPair CurrentPair; |
1273 | memoryaccess_def_iterator DefIterator; |
1274 | MemoryLocation Location; |
1275 | MemoryAccess *OriginalAccess = nullptr; |
1276 | DominatorTree *DT = nullptr; |
1277 | bool WalkingPhi = false; |
1278 | bool *PerformedPhiTranslation = nullptr; |
1279 | }; |
1280 | |
1281 | inline upward_defs_iterator |
1282 | upward_defs_begin(const MemoryAccessPair &Pair, DominatorTree &DT, |
1283 | bool *PerformedPhiTranslation = nullptr) { |
1284 | return upward_defs_iterator(Pair, &DT, PerformedPhiTranslation); |
1285 | } |
1286 | |
1287 | inline upward_defs_iterator upward_defs_end() { return upward_defs_iterator(); } |
1288 | |
1289 | inline iterator_range<upward_defs_iterator> |
1290 | upward_defs(const MemoryAccessPair &Pair, DominatorTree &DT) { |
1291 | return make_range(upward_defs_begin(Pair, DT), upward_defs_end()); |
1292 | } |
1293 | |
1294 | /// Walks the defining accesses of MemoryDefs. Stops after we hit something that |
1295 | /// has no defining use (e.g. a MemoryPhi or liveOnEntry). Note that, when |
1296 | /// comparing against a null def_chain_iterator, this will compare equal only |
1297 | /// after walking said Phi/liveOnEntry. |
1298 | /// |
1299 | /// The UseOptimizedChain flag specifies whether to walk the clobbering |
1300 | /// access chain, or all the accesses. |
1301 | /// |
1302 | /// Normally, MemoryDef are all just def/use linked together, so a def_chain on |
1303 | /// a MemoryDef will walk all MemoryDefs above it in the program until it hits |
1304 | /// a phi node. The optimized chain walks the clobbering access of a store. |
1305 | /// So if you are just trying to find, given a store, what the next |
1306 | /// thing that would clobber the same memory is, you want the optimized chain. |
1307 | template <class T, bool UseOptimizedChain = false> |
1308 | struct def_chain_iterator |
1309 | : public iterator_facade_base<def_chain_iterator<T, UseOptimizedChain>, |
1310 | std::forward_iterator_tag, MemoryAccess *> { |
1311 | def_chain_iterator() : MA(nullptr) {} |
1312 | def_chain_iterator(T MA) : MA(MA) {} |
1313 | |
1314 | T operator*() const { return MA; } |
1315 | |
1316 | def_chain_iterator &operator++() { |
1317 | // N.B. liveOnEntry has a null defining access. |
1318 | if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) { |
1319 | if (UseOptimizedChain && MUD->isOptimized()) |
1320 | MA = MUD->getOptimized(); |
1321 | else |
1322 | MA = MUD->getDefiningAccess(); |
1323 | } else { |
1324 | MA = nullptr; |
1325 | } |
1326 | |
1327 | return *this; |
1328 | } |
1329 | |
1330 | bool operator==(const def_chain_iterator &O) const { return MA == O.MA; } |
1331 | |
1332 | private: |
1333 | T MA; |
1334 | }; |
1335 | |
1336 | template <class T> |
1337 | inline iterator_range<def_chain_iterator<T>> |
1338 | def_chain(T MA, MemoryAccess *UpTo = nullptr) { |
1339 | #ifdef EXPENSIVE_CHECKS |
1340 | assert((!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator<T>()) &&(((!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator< T>()) && "UpTo isn't in the def chain!") ? static_cast <void> (0) : __assert_fail ("(!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator<T>()) && \"UpTo isn't in the def chain!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 1341, __PRETTY_FUNCTION__)) |
1341 | "UpTo isn't in the def chain!")(((!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator< T>()) && "UpTo isn't in the def chain!") ? static_cast <void> (0) : __assert_fail ("(!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator<T>()) && \"UpTo isn't in the def chain!\"" , "/build/llvm-toolchain-snapshot-12~++20201217111122+722247c8124/llvm/include/llvm/Analysis/MemorySSA.h" , 1341, __PRETTY_FUNCTION__)); |
1342 | #endif |
1343 | return make_range(def_chain_iterator<T>(MA), def_chain_iterator<T>(UpTo)); |
1344 | } |
1345 | |
1346 | template <class T> |
1347 | inline iterator_range<def_chain_iterator<T, true>> optimized_def_chain(T MA) { |
1348 | return make_range(def_chain_iterator<T, true>(MA), |
1349 | def_chain_iterator<T, true>(nullptr)); |
1350 | } |
1351 | |
1352 | } // end namespace llvm |
1353 | |
1354 | #endif // LLVM_ANALYSIS_MEMORYSSA_H |