Bug Summary

File:llvm/lib/Analysis/MemorySSA.cpp
Warning:line 2019, column 5
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name MemorySSA.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/lib/Analysis -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../x86_64-linux-gnu/include -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/lib/Analysis -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-04-05-202135-9119-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/llvm/lib/Analysis/MemorySSA.cpp

/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/llvm/lib/Analysis/MemorySSA.cpp

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

/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Analysis/MemorySSA.h

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
107namespace llvm {
108
109/// Enables memory ssa as a dependency for loop passes.
110extern cl::opt<bool> EnableMSSALoopDependency;
111
112class AllocaInst;
113class Function;
114class Instruction;
115class MemoryAccess;
116class MemorySSAWalker;
117class LLVMContext;
118class raw_ostream;
119
120namespace MSSAHelpers {
121
122struct AllAccessTag {};
123struct DefsOnlyTag {};
124
125} // end namespace MSSAHelpers
126
127enum : unsigned {
128 // Used to signify what the default invalid ID is for MemoryAccess's
129 // getID()
130 INVALID_MEMORYACCESS_ID = -1U
131};
132
133template <class T> class memoryaccess_def_iterator_base;
134using memoryaccess_def_iterator = memoryaccess_def_iterator_base<MemoryAccess>;
135using const_memoryaccess_def_iterator =
136 memoryaccess_def_iterator_base<const MemoryAccess>;
137
138// The base for all memory accesses. All memory accesses in a block are
139// linked together using an intrusive list.
140class MemoryAccess
141 : public DerivedUser,
142 public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>,
143 public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>> {
144public:
145 using AllAccessType =
146 ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>;
147 using DefsOnlyType =
148 ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>>;
149
150 MemoryAccess(const MemoryAccess &) = delete;
151 MemoryAccess &operator=(const MemoryAccess &) = delete;
152
153 void *operator new(size_t) = delete;
154
155 // Methods for support type inquiry through isa, cast, and
156 // dyn_cast
157 static bool classof(const Value *V) {
158 unsigned ID = V->getValueID();
159 return ID == MemoryUseVal || ID == MemoryPhiVal || ID == MemoryDefVal;
160 }
161
162 BasicBlock *getBlock() const { return Block; }
163
164 void print(raw_ostream &OS) const;
165 void dump() const;
166
167 /// The user iterators for a memory access
168 using iterator = user_iterator;
169 using const_iterator = const_user_iterator;
170
171 /// This iterator walks over all of the defs in a given
172 /// MemoryAccess. For MemoryPhi nodes, this walks arguments. For
173 /// MemoryUse/MemoryDef, this walks the defining access.
174 memoryaccess_def_iterator defs_begin();
175 const_memoryaccess_def_iterator defs_begin() const;
176 memoryaccess_def_iterator defs_end();
177 const_memoryaccess_def_iterator defs_end() const;
178
179 /// Get the iterators for the all access list and the defs only list
180 /// We default to the all access list.
181 AllAccessType::self_iterator getIterator() {
182 return this->AllAccessType::getIterator();
183 }
184 AllAccessType::const_self_iterator getIterator() const {
185 return this->AllAccessType::getIterator();
186 }
187 AllAccessType::reverse_self_iterator getReverseIterator() {
188 return this->AllAccessType::getReverseIterator();
189 }
190 AllAccessType::const_reverse_self_iterator getReverseIterator() const {
191 return this->AllAccessType::getReverseIterator();
192 }
193 DefsOnlyType::self_iterator getDefsIterator() {
194 return this->DefsOnlyType::getIterator();
195 }
196 DefsOnlyType::const_self_iterator getDefsIterator() const {
197 return this->DefsOnlyType::getIterator();
198 }
199 DefsOnlyType::reverse_self_iterator getReverseDefsIterator() {
200 return this->DefsOnlyType::getReverseIterator();
201 }
202 DefsOnlyType::const_reverse_self_iterator getReverseDefsIterator() const {
203 return this->DefsOnlyType::getReverseIterator();
204 }
205
206protected:
207 friend class MemoryDef;
208 friend class MemoryPhi;
209 friend class MemorySSA;
210 friend class MemoryUse;
211 friend class MemoryUseOrDef;
212
213 /// Used by MemorySSA to change the block of a MemoryAccess when it is
214 /// moved.
215 void setBlock(BasicBlock *BB) { Block = BB; }
216
217 /// Used for debugging and tracking things about MemoryAccesses.
218 /// Guaranteed unique among MemoryAccesses, no guarantees otherwise.
219 inline unsigned getID() const;
220
221 MemoryAccess(LLVMContext &C, unsigned Vty, DeleteValueTy DeleteValue,
222 BasicBlock *BB, unsigned NumOperands)
223 : DerivedUser(Type::getVoidTy(C), Vty, nullptr, NumOperands, DeleteValue),
224 Block(BB) {}
225
226 // Use deleteValue() to delete a generic MemoryAccess.
227 ~MemoryAccess() = default;
228
229private:
230 BasicBlock *Block;
231};
232
233template <>
234struct ilist_alloc_traits<MemoryAccess> {
235 static void deleteNode(MemoryAccess *MA) { MA->deleteValue(); }
236};
237
238inline raw_ostream &operator<<(raw_ostream &OS, const MemoryAccess &MA) {
239 MA.print(OS);
240 return OS;
241}
242
243/// Class that has the common methods + fields of memory uses/defs. It's
244/// a little awkward to have, but there are many cases where we want either a
245/// use or def, and there are many cases where uses are needed (defs aren't
246/// acceptable), and vice-versa.
247///
248/// This class should never be instantiated directly; make a MemoryUse or
249/// MemoryDef instead.
250class MemoryUseOrDef : public MemoryAccess {
251public:
252 void *operator new(size_t) = delete;
253
254 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
;
255
256 /// Get the instruction that this MemoryUse represents.
257 Instruction *getMemoryInst() const { return MemoryInstruction; }
258
259 /// Get the access that produces the memory state used by this Use.
260 MemoryAccess *getDefiningAccess() const { return getOperand(0); }
261
262 static bool classof(const Value *MA) {
263 return MA->getValueID() == MemoryUseVal || MA->getValueID() == MemoryDefVal;
264 }
265
266 // Sadly, these have to be public because they are needed in some of the
267 // iterators.
268 inline bool isOptimized() const;
269 inline MemoryAccess *getOptimized() const;
270 inline void setOptimized(MemoryAccess *);
271
272 // Retrieve AliasResult type of the optimized access. Ideally this would be
273 // returned by the caching walker and may go away in the future.
274 Optional<AliasResult> getOptimizedAccessType() const {
275 return isOptimized() ? OptimizedAccessAlias : None;
276 }
277
278 /// Reset the ID of what this MemoryUse was optimized to, causing it to
279 /// be rewalked by the walker if necessary.
280 /// This really should only be called by tests.
281 inline void resetOptimized();
282
283protected:
284 friend class MemorySSA;
285 friend class MemorySSAUpdater;
286
287 MemoryUseOrDef(LLVMContext &C, MemoryAccess *DMA, unsigned Vty,
288 DeleteValueTy DeleteValue, Instruction *MI, BasicBlock *BB,
289 unsigned NumOperands)
290 : MemoryAccess(C, Vty, DeleteValue, BB, NumOperands),
291 MemoryInstruction(MI), OptimizedAccessAlias(MayAlias) {
292 setDefiningAccess(DMA);
293 }
294
295 // Use deleteValue() to delete a generic MemoryUseOrDef.
296 ~MemoryUseOrDef() = default;
297
298 void setOptimizedAccessType(Optional<AliasResult> AR) {
299 OptimizedAccessAlias = AR;
300 }
301
302 void setDefiningAccess(MemoryAccess *DMA, bool Optimized = false,
303 Optional<AliasResult> AR = MayAlias) {
304 if (!Optimized) {
305 setOperand(0, DMA);
306 return;
307 }
308 setOptimized(DMA);
309 setOptimizedAccessType(AR);
310 }
311
312private:
313 Instruction *MemoryInstruction;
314 Optional<AliasResult> OptimizedAccessAlias;
315};
316
317/// Represents read-only accesses to memory
318///
319/// In particular, the set of Instructions that will be represented by
320/// MemoryUse's is exactly the set of Instructions for which
321/// AliasAnalysis::getModRefInfo returns "Ref".
322class MemoryUse final : public MemoryUseOrDef {
323public:
324 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
;
325
326 MemoryUse(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB)
327 : MemoryUseOrDef(C, DMA, MemoryUseVal, deleteMe, MI, BB,
328 /*NumOperands=*/1) {}
329
330 // allocate space for exactly one operand
331 void *operator new(size_t s) { return User::operator new(s, 1); }
332
333 static bool classof(const Value *MA) {
334 return MA->getValueID() == MemoryUseVal;
335 }
336
337 void print(raw_ostream &OS) const;
338
339 void setOptimized(MemoryAccess *DMA) {
340 OptimizedID = DMA->getID();
341 setOperand(0, DMA);
342 }
343
344 bool isOptimized() const {
345 return getDefiningAccess() && OptimizedID == getDefiningAccess()->getID();
346 }
347
348 MemoryAccess *getOptimized() const {
349 return getDefiningAccess();
350 }
351
352 void resetOptimized() {
353 OptimizedID = INVALID_MEMORYACCESS_ID;
354 }
355
356protected:
357 friend class MemorySSA;
358
359private:
360 static void deleteMe(DerivedUser *Self);
361
362 unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
363};
364
365template <>
366struct OperandTraits<MemoryUse> : public FixedNumOperandTraits<MemoryUse, 1> {};
367DEFINE_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-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Analysis/MemorySSA.h"
, 367, __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-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Analysis/MemorySSA.h"
, 367, __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
); }
368
369/// Represents a read-write access to memory, whether it is a must-alias,
370/// or a may-alias.
371///
372/// In particular, the set of Instructions that will be represented by
373/// MemoryDef's is exactly the set of Instructions for which
374/// AliasAnalysis::getModRefInfo returns "Mod" or "ModRef".
375/// Note that, in order to provide def-def chains, all defs also have a use
376/// associated with them. This use points to the nearest reaching
377/// MemoryDef/MemoryPhi.
378class MemoryDef final : public MemoryUseOrDef {
379public:
380 friend class MemorySSA;
381
382 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
;
383
384 MemoryDef(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB,
385 unsigned Ver)
386 : MemoryUseOrDef(C, DMA, MemoryDefVal, deleteMe, MI, BB,
387 /*NumOperands=*/2),
388 ID(Ver) {}
389
390 // allocate space for exactly two operands
391 void *operator new(size_t s) { return User::operator new(s, 2); }
392
393 static bool classof(const Value *MA) {
394 return MA->getValueID() == MemoryDefVal;
395 }
396
397 void setOptimized(MemoryAccess *MA) {
398 setOperand(1, MA);
399 OptimizedID = MA->getID();
400 }
401
402 MemoryAccess *getOptimized() const {
403 return cast_or_null<MemoryAccess>(getOperand(1));
404 }
405
406 bool isOptimized() const {
407 return getOptimized() && OptimizedID == getOptimized()->getID();
408 }
409
410 void resetOptimized() {
411 OptimizedID = INVALID_MEMORYACCESS_ID;
412 setOperand(1, nullptr);
413 }
414
415 void print(raw_ostream &OS) const;
416
417 unsigned getID() const { return ID; }
418
419private:
420 static void deleteMe(DerivedUser *Self);
421
422 const unsigned ID;
423 unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
424};
425
426template <>
427struct OperandTraits<MemoryDef> : public FixedNumOperandTraits<MemoryDef, 2> {};
428DEFINE_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-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Analysis/MemorySSA.h"
, 428, __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-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Analysis/MemorySSA.h"
, 428, __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
); }
429
430template <>
431struct OperandTraits<MemoryUseOrDef> {
432 static Use *op_begin(MemoryUseOrDef *MUD) {
433 if (auto *MU = dyn_cast<MemoryUse>(MUD))
434 return OperandTraits<MemoryUse>::op_begin(MU);
435 return OperandTraits<MemoryDef>::op_begin(cast<MemoryDef>(MUD));
436 }
437
438 static Use *op_end(MemoryUseOrDef *MUD) {
439 if (auto *MU = dyn_cast<MemoryUse>(MUD))
440 return OperandTraits<MemoryUse>::op_end(MU);
441 return OperandTraits<MemoryDef>::op_end(cast<MemoryDef>(MUD));
442 }
443
444 static unsigned operands(const MemoryUseOrDef *MUD) {
445 if (const auto *MU = dyn_cast<MemoryUse>(MUD))
446 return OperandTraits<MemoryUse>::operands(MU);
447 return OperandTraits<MemoryDef>::operands(cast<MemoryDef>(MUD));
448 }
449};
450DEFINE_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-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Analysis/MemorySSA.h"
, 450, __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-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Analysis/MemorySSA.h"
, 450, __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); }
451
452/// Represents phi nodes for memory accesses.
453///
454/// These have the same semantic as regular phi nodes, with the exception that
455/// only one phi will ever exist in a given basic block.
456/// Guaranteeing one phi per block means guaranteeing there is only ever one
457/// valid reaching MemoryDef/MemoryPHI along each path to the phi node.
458/// This is ensured by not allowing disambiguation of the RHS of a MemoryDef or
459/// a MemoryPhi's operands.
460/// That is, given
461/// if (a) {
462/// store %a
463/// store %b
464/// }
465/// it *must* be transformed into
466/// if (a) {
467/// 1 = MemoryDef(liveOnEntry)
468/// store %a
469/// 2 = MemoryDef(1)
470/// store %b
471/// }
472/// and *not*
473/// if (a) {
474/// 1 = MemoryDef(liveOnEntry)
475/// store %a
476/// 2 = MemoryDef(liveOnEntry)
477/// store %b
478/// }
479/// even if the two stores do not conflict. Otherwise, both 1 and 2 reach the
480/// end of the branch, and if there are not two phi nodes, one will be
481/// disconnected completely from the SSA graph below that point.
482/// Because MemoryUse's do not generate new definitions, they do not have this
483/// issue.
484class MemoryPhi final : public MemoryAccess {
485 // allocate space for exactly zero operands
486 void *operator new(size_t s) { return User::operator new(s); }
487
488public:
489 /// Provide fast operand accessors
490 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
;
491
492 MemoryPhi(LLVMContext &C, BasicBlock *BB, unsigned Ver, unsigned NumPreds = 0)
493 : MemoryAccess(C, MemoryPhiVal, deleteMe, BB, 0), ID(Ver),
494 ReservedSpace(NumPreds) {
495 allocHungoffUses(ReservedSpace);
496 }
497
498 // Block iterator interface. This provides access to the list of incoming
499 // basic blocks, which parallels the list of incoming values.
500 using block_iterator = BasicBlock **;
501 using const_block_iterator = BasicBlock *const *;
502
503 block_iterator block_begin() {
504 return reinterpret_cast<block_iterator>(op_begin() + ReservedSpace);
505 }
506
507 const_block_iterator block_begin() const {
508 return reinterpret_cast<const_block_iterator>(op_begin() + ReservedSpace);
509 }
510
511 block_iterator block_end() { return block_begin() + getNumOperands(); }
512
513 const_block_iterator block_end() const {
514 return block_begin() + getNumOperands();
515 }
516
517 iterator_range<block_iterator> blocks() {
518 return make_range(block_begin(), block_end());
519 }
520
521 iterator_range<const_block_iterator> blocks() const {
522 return make_range(block_begin(), block_end());
523 }
524
525 op_range incoming_values() { return operands(); }
526
527 const_op_range incoming_values() const { return operands(); }
528
529 /// Return the number of incoming edges
530 unsigned getNumIncomingValues() const { return getNumOperands(); }
531
532 /// Return incoming value number x
533 MemoryAccess *getIncomingValue(unsigned I) const { return getOperand(I); }
534 void setIncomingValue(unsigned I, MemoryAccess *V) {
535 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-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Analysis/MemorySSA.h"
, 535, __PRETTY_FUNCTION__))
;
536 setOperand(I, V);
537 }
538
539 static unsigned getOperandNumForIncomingValue(unsigned I) { return I; }
540 static unsigned getIncomingValueNumForOperand(unsigned I) { return I; }
541
542 /// Return incoming basic block number @p i.
543 BasicBlock *getIncomingBlock(unsigned I) const { return block_begin()[I]; }
544
545 /// Return incoming basic block corresponding
546 /// to an operand of the PHI.
547 BasicBlock *getIncomingBlock(const Use &U) const {
548 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-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Analysis/MemorySSA.h"
, 548, __PRETTY_FUNCTION__))
;
549 return getIncomingBlock(unsigned(&U - op_begin()));
550 }
551
552 /// Return incoming basic block corresponding
553 /// to value use iterator.
554 BasicBlock *getIncomingBlock(MemoryAccess::const_user_iterator I) const {
555 return getIncomingBlock(I.getUse());
556 }
557
558 void setIncomingBlock(unsigned I, BasicBlock *BB) {
559 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-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Analysis/MemorySSA.h"
, 559, __PRETTY_FUNCTION__))
;
560 block_begin()[I] = BB;
561 }
562
563 /// Add an incoming value to the end of the PHI list
564 void addIncoming(MemoryAccess *V, BasicBlock *BB) {
565 if (getNumOperands() == ReservedSpace)
566 growOperands(); // Get more space!
567 // Initialize some new operands.
568 setNumHungOffUseOperands(getNumOperands() + 1);
569 setIncomingValue(getNumOperands() - 1, V);
570 setIncomingBlock(getNumOperands() - 1, BB);
571 }
572
573 /// Return the first index of the specified basic
574 /// block in the value list for this PHI. Returns -1 if no instance.
575 int getBasicBlockIndex(const BasicBlock *BB) const {
576 for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
577 if (block_begin()[I] == BB)
578 return I;
579 return -1;
580 }
581
582 MemoryAccess *getIncomingValueForBlock(const BasicBlock *BB) const {
583 int Idx = getBasicBlockIndex(BB);
584 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-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Analysis/MemorySSA.h"
, 584, __PRETTY_FUNCTION__))
;
585 return getIncomingValue(Idx);
586 }
587
588 // After deleting incoming position I, the order of incoming may be changed.
589 void unorderedDeleteIncoming(unsigned I) {
590 unsigned E = getNumOperands();
591 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-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Analysis/MemorySSA.h"
, 591, __PRETTY_FUNCTION__))
;
592 // MemoryPhi must have at least two incoming values, otherwise the MemoryPhi
593 // itself should be deleted.
594 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-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Analysis/MemorySSA.h"
, 595, __PRETTY_FUNCTION__))
595 "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-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Analysis/MemorySSA.h"
, 595, __PRETTY_FUNCTION__))
;
596 setIncomingValue(I, getIncomingValue(E - 1));
597 setIncomingBlock(I, block_begin()[E - 1]);
598 setOperand(E - 1, nullptr);
599 block_begin()[E - 1] = nullptr;
600 setNumHungOffUseOperands(getNumOperands() - 1);
601 }
602
603 // After deleting entries that satisfy Pred, remaining entries may have
604 // changed order.
605 template <typename Fn> void unorderedDeleteIncomingIf(Fn &&Pred) {
606 for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
607 if (Pred(getIncomingValue(I), getIncomingBlock(I))) {
608 unorderedDeleteIncoming(I);
609 E = getNumOperands();
610 --I;
611 }
612 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-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Analysis/MemorySSA.h"
, 613, __PRETTY_FUNCTION__))
613 "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-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Analysis/MemorySSA.h"
, 613, __PRETTY_FUNCTION__))
;
614 }
615
616 // After deleting incoming block BB, the incoming blocks order may be changed.
617 void unorderedDeleteIncomingBlock(const BasicBlock *BB) {
618 unorderedDeleteIncomingIf(
619 [&](const MemoryAccess *, const BasicBlock *B) { return BB == B; });
620 }
621
622 // After deleting incoming memory access MA, the incoming accesses order may
623 // be changed.
624 void unorderedDeleteIncomingValue(const MemoryAccess *MA) {
625 unorderedDeleteIncomingIf(
626 [&](const MemoryAccess *M, const BasicBlock *) { return MA == M; });
627 }
628
629 static bool classof(const Value *V) {
630 return V->getValueID() == MemoryPhiVal;
631 }
632
633 void print(raw_ostream &OS) const;
634
635 unsigned getID() const { return ID; }
636
637protected:
638 friend class MemorySSA;
639
640 /// this is more complicated than the generic
641 /// User::allocHungoffUses, because we have to allocate Uses for the incoming
642 /// values and pointers to the incoming blocks, all in one allocation.
643 void allocHungoffUses(unsigned N) {
644 User::allocHungoffUses(N, /* IsPhi */ true);
645 }
646
647private:
648 // For debugging only
649 const unsigned ID;
650 unsigned ReservedSpace;
651
652 /// This grows the operand list in response to a push_back style of
653 /// operation. This grows the number of ops by 1.5 times.
654 void growOperands() {
655 unsigned E = getNumOperands();
656 // 2 op PHI nodes are VERY common, so reserve at least enough for that.
657 ReservedSpace = std::max(E + E / 2, 2u);
658 growHungoffUses(ReservedSpace, /* IsPhi */ true);
659 }
660
661 static void deleteMe(DerivedUser *Self);
662};
663
664inline unsigned MemoryAccess::getID() const {
665 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-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Analysis/MemorySSA.h"
, 666, __PRETTY_FUNCTION__))
666 "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-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Analysis/MemorySSA.h"
, 666, __PRETTY_FUNCTION__))
;
667 if (const auto *MD = dyn_cast<MemoryDef>(this))
668 return MD->getID();
669 return cast<MemoryPhi>(this)->getID();
670}
671
672inline bool MemoryUseOrDef::isOptimized() const {
673 if (const auto *MD = dyn_cast<MemoryDef>(this))
674 return MD->isOptimized();
675 return cast<MemoryUse>(this)->isOptimized();
676}
677
678inline MemoryAccess *MemoryUseOrDef::getOptimized() const {
679 if (const auto *MD = dyn_cast<MemoryDef>(this))
680 return MD->getOptimized();
681 return cast<MemoryUse>(this)->getOptimized();
682}
683
684inline void MemoryUseOrDef::setOptimized(MemoryAccess *MA) {
685 if (auto *MD = dyn_cast<MemoryDef>(this))
686 MD->setOptimized(MA);
687 else
688 cast<MemoryUse>(this)->setOptimized(MA);
689}
690
691inline void MemoryUseOrDef::resetOptimized() {
692 if (auto *MD = dyn_cast<MemoryDef>(this))
693 MD->resetOptimized();
694 else
695 cast<MemoryUse>(this)->resetOptimized();
696}
697
698template <> struct OperandTraits<MemoryPhi> : public HungoffOperandTraits<2> {};
699DEFINE_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-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Analysis/MemorySSA.h"
, 699, __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-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Analysis/MemorySSA.h"
, 699, __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
); }
700
701/// Encapsulates MemorySSA, including all data associated with memory
702/// accesses.
703class MemorySSA {
704public:
705 MemorySSA(Function &, AliasAnalysis *, DominatorTree *);
706
707 // MemorySSA must remain where it's constructed; Walkers it creates store
708 // pointers to it.
709 MemorySSA(MemorySSA &&) = delete;
710
711 ~MemorySSA();
712
713 MemorySSAWalker *getWalker();
714 MemorySSAWalker *getSkipSelfWalker();
715
716 /// Given a memory Mod/Ref'ing instruction, get the MemorySSA
717 /// access associated with it. If passed a basic block gets the memory phi
718 /// node that exists for that block, if there is one. Otherwise, this will get
719 /// a MemoryUseOrDef.
720 MemoryUseOrDef *getMemoryAccess(const Instruction *I) const {
721 return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I));
722 }
723
724 MemoryPhi *getMemoryAccess(const BasicBlock *BB) const {
725 return cast_or_null<MemoryPhi>(ValueToMemoryAccess.lookup(cast<Value>(BB)));
23
'BB' is a 'Value'
24
Assuming null pointer is passed into cast
25
Returning null pointer, which participates in a condition later
726 }
727
728 DominatorTree &getDomTree() const { return *DT; }
729
730 void dump() const;
731 void print(raw_ostream &) const;
732
733 /// Return true if \p MA represents the live on entry value
734 ///
735 /// Loads and stores from pointer arguments and other global values may be
736 /// defined by memory operations that do not occur in the current function, so
737 /// they may be live on entry to the function. MemorySSA represents such
738 /// memory state by the live on entry definition, which is guaranteed to occur
739 /// before any other memory access in the function.
740 inline bool isLiveOnEntryDef(const MemoryAccess *MA) const {
741 return MA == LiveOnEntryDef.get();
742 }
743
744 inline MemoryAccess *getLiveOnEntryDef() const {
745 return LiveOnEntryDef.get();
746 }
747
748 // Sadly, iplists, by default, owns and deletes pointers added to the
749 // list. It's not currently possible to have two iplists for the same type,
750 // where one owns the pointers, and one does not. This is because the traits
751 // are per-type, not per-tag. If this ever changes, we should make the
752 // DefList an iplist.
753 using AccessList = iplist<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>;
754 using DefsList =
755 simple_ilist<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>>;
756
757 /// Return the list of MemoryAccess's for a given basic block.
758 ///
759 /// This list is not modifiable by the user.
760 const AccessList *getBlockAccesses(const BasicBlock *BB) const {
761 return getWritableBlockAccesses(BB);
6
Calling 'MemorySSA::getWritableBlockAccesses'
10
Returning from 'MemorySSA::getWritableBlockAccesses'
11
Returning pointer, which participates in a condition later
12
Returning pointer
762 }
763
764 /// Return the list of MemoryDef's and MemoryPhi's for a given basic
765 /// block.
766 ///
767 /// This list is not modifiable by the user.
768 const DefsList *getBlockDefs(const BasicBlock *BB) const {
769 return getWritableBlockDefs(BB);
16
Calling 'MemorySSA::getWritableBlockDefs'
19
Returning from 'MemorySSA::getWritableBlockDefs'
20
Returning pointer, which participates in a condition later
770 }
771
772 /// Given two memory accesses in the same basic block, determine
773 /// whether MemoryAccess \p A dominates MemoryAccess \p B.
774 bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const;
775
776 /// Given two memory accesses in potentially different blocks,
777 /// determine whether MemoryAccess \p A dominates MemoryAccess \p B.
778 bool dominates(const MemoryAccess *A, const MemoryAccess *B) const;
779
780 /// Given a MemoryAccess and a Use, determine whether MemoryAccess \p A
781 /// dominates Use \p B.
782 bool dominates(const MemoryAccess *A, const Use &B) const;
783
784 /// Verify that MemorySSA is self consistent (IE definitions dominate
785 /// all uses, uses appear in the right places). This is used by unit tests.
786 void verifyMemorySSA() const;
787
788 /// Used in various insertion functions to specify whether we are talking
789 /// about the beginning or end of a block.
790 enum InsertionPlace { Beginning, End, BeforeTerminator };
791
792protected:
793 // Used by Memory SSA annotater, dumpers, and wrapper pass
794 friend class MemorySSAAnnotatedWriter;
795 friend class MemorySSAPrinterLegacyPass;
796 friend class MemorySSAUpdater;
797
798 void verifyOrderingDominationAndDefUses(Function &F) const;
799 void verifyDominationNumbers(const Function &F) const;
800 void verifyPrevDefInPhis(Function &F) const;
801
802 // This is used by the use optimizer and updater.
803 AccessList *getWritableBlockAccesses(const BasicBlock *BB) const {
804 auto It = PerBlockAccesses.find(BB);
805 return It == PerBlockAccesses.end() ? nullptr : It->second.get();
7
'?' condition is false
8
Returning pointer, which participates in a condition later
9
Returning pointer
806 }
807
808 // This is used by the use optimizer and updater.
809 DefsList *getWritableBlockDefs(const BasicBlock *BB) const {
810 auto It = PerBlockDefs.find(BB);
811 return It == PerBlockDefs.end() ? nullptr : It->second.get();
17
'?' condition is false
18
Returning pointer, which participates in a condition later
812 }
813
814 // These is used by the updater to perform various internal MemorySSA
815 // machinsations. They do not always leave the IR in a correct state, and
816 // relies on the updater to fixup what it breaks, so it is not public.
817
818 void moveTo(MemoryUseOrDef *What, BasicBlock *BB, AccessList::iterator Where);
819 void moveTo(MemoryAccess *What, BasicBlock *BB, InsertionPlace Point);
820
821 // Rename the dominator tree branch rooted at BB.
822 void renamePass(BasicBlock *BB, MemoryAccess *IncomingVal,
823 SmallPtrSetImpl<BasicBlock *> &Visited) {
824 renamePass(DT->getNode(BB), IncomingVal, Visited, true, true);
825 }
826
827 void removeFromLookups(MemoryAccess *);
828 void removeFromLists(MemoryAccess *, bool ShouldDelete = true);
829 void insertIntoListsForBlock(MemoryAccess *, const BasicBlock *,
830 InsertionPlace);
831 void insertIntoListsBefore(MemoryAccess *, const BasicBlock *,
832 AccessList::iterator);
833 MemoryUseOrDef *createDefinedAccess(Instruction *, MemoryAccess *,
834 const MemoryUseOrDef *Template = nullptr,
835 bool CreationMustSucceed = true);
836
837private:
838 template <class AliasAnalysisType> class ClobberWalkerBase;
839 template <class AliasAnalysisType> class CachingWalker;
840 template <class AliasAnalysisType> class SkipSelfWalker;
841 class OptimizeUses;
842
843 CachingWalker<AliasAnalysis> *getWalkerImpl();
844 void buildMemorySSA(BatchAAResults &BAA);
845
846 void prepareForMoveTo(MemoryAccess *, BasicBlock *);
847 void verifyUseInDefs(MemoryAccess *, MemoryAccess *) const;
848
849 using AccessMap = DenseMap<const BasicBlock *, std::unique_ptr<AccessList>>;
850 using DefsMap = DenseMap<const BasicBlock *, std::unique_ptr<DefsList>>;
851
852 void markUnreachableAsLiveOnEntry(BasicBlock *BB);
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
897class MemorySSAUtil {
898protected:
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.
909class MemorySSAPrinterLegacyPass : public FunctionPass {
910public:
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///
921class MemorySSAAnalysis : public AnalysisInfoMixin<MemorySSAAnalysis> {
922 friend AnalysisInfoMixin<MemorySSAAnalysis>;
923
924 static AnalysisKey Key;
925
926public:
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.
945class MemorySSAPrinterPass : public PassInfoMixin<MemorySSAPrinterPass> {
946 raw_ostream &OS;
947
948public:
949 explicit MemorySSAPrinterPass(raw_ostream &OS) : OS(OS) {}
950
951 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
952};
953
954/// Verifier pass for \c MemorySSA.
955struct MemorySSAVerifierPass : PassInfoMixin<MemorySSAVerifierPass> {
956 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
957};
958
959/// Legacy analysis pass which computes \c MemorySSA.
960class MemorySSAWrapperPass : public FunctionPass {
961public:
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
976private:
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.
991class MemorySSAWalker {
992public:
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-13~++20210405022414+5f57793c4fe4/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
1051protected:
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.
1059class DoNothingMemorySSAWalker final : public MemorySSAWalker {
1060public:
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
1070using MemoryAccessPair = std::pair<MemoryAccess *, MemoryLocation>;
1071using 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.
1075template <class T>
1076class 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
1082public:
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-13~++20210405022414+5f57793c4fe4/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-13~++20210405022414+5f57793c4fe4/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-13~++20210405022414+5f57793c4fe4/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
1125private:
1126 T *Access = nullptr;
1127 unsigned ArgNo = 0;
1128};
1129
1130inline memoryaccess_def_iterator MemoryAccess::defs_begin() {
1131 return memoryaccess_def_iterator(this);
1132}
1133
1134inline const_memoryaccess_def_iterator MemoryAccess::defs_begin() const {
1135 return const_memoryaccess_def_iterator(this);
1136}
1137
1138inline memoryaccess_def_iterator MemoryAccess::defs_end() {
1139 return memoryaccess_def_iterator();
1140}
1141
1142inline 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.
1148template <> 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
1157template <> 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.
1174class 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
1180public:
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-13~++20210405022414+5f57793c4fe4/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-13~++20210405022414+5f57793c4fe4/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-13~++20210405022414+5f57793c4fe4/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-13~++20210405022414+5f57793c4fe4/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
1216private:
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
1222 void fillInCurrentPair() {
1223 CurrentPair.first = *DefIterator;
1224 CurrentPair.second = Location;
1225 if (WalkingPhi && Location.Ptr) {
1226 // Mark size as unknown, if the location is not guaranteed to be
1227 // loop-invariant for any possible loop in the function. Setting the size
1228 // to unknown guarantees that any memory accesses that access locations
1229 // after the pointer are considered as clobbers, which is important to
1230 // catch loop carried dependences.
1231 if (Location.Ptr &&
1232 !IsGuaranteedLoopInvariant(const_cast<Value *>(Location.Ptr)))
1233 CurrentPair.second =
1234 Location.getWithNewSize(LocationSize::beforeOrAfterPointer());
1235 PHITransAddr Translator(
1236 const_cast<Value *>(Location.Ptr),
1237 OriginalAccess->getBlock()->getModule()->getDataLayout(), nullptr);
1238
1239 if (!Translator.PHITranslateValue(OriginalAccess->getBlock(),
1240 DefIterator.getPhiArgBlock(), DT,
1241 true)) {
1242 Value *TransAddr = Translator.getAddr();
1243 if (TransAddr != Location.Ptr) {
1244 CurrentPair.second = CurrentPair.second.getWithNewPtr(TransAddr);
1245
1246 if (TransAddr &&
1247 !IsGuaranteedLoopInvariant(const_cast<Value *>(TransAddr)))
1248 CurrentPair.second = CurrentPair.second.getWithNewSize(
1249 LocationSize::beforeOrAfterPointer());
1250
1251 if (PerformedPhiTranslation)
1252 *PerformedPhiTranslation = true;
1253 }
1254 }
1255 }
1256 }
1257
1258 MemoryAccessPair CurrentPair;
1259 memoryaccess_def_iterator DefIterator;
1260 MemoryLocation Location;
1261 MemoryAccess *OriginalAccess = nullptr;
1262 DominatorTree *DT = nullptr;
1263 bool WalkingPhi = false;
1264 bool *PerformedPhiTranslation = nullptr;
1265};
1266
1267inline upward_defs_iterator
1268upward_defs_begin(const MemoryAccessPair &Pair, DominatorTree &DT,
1269 bool *PerformedPhiTranslation = nullptr) {
1270 return upward_defs_iterator(Pair, &DT, PerformedPhiTranslation);
1271}
1272
1273inline upward_defs_iterator upward_defs_end() { return upward_defs_iterator(); }
1274
1275inline iterator_range<upward_defs_iterator>
1276upward_defs(const MemoryAccessPair &Pair, DominatorTree &DT) {
1277 return make_range(upward_defs_begin(Pair, DT), upward_defs_end());
1278}
1279
1280/// Walks the defining accesses of MemoryDefs. Stops after we hit something that
1281/// has no defining use (e.g. a MemoryPhi or liveOnEntry). Note that, when
1282/// comparing against a null def_chain_iterator, this will compare equal only
1283/// after walking said Phi/liveOnEntry.
1284///
1285/// The UseOptimizedChain flag specifies whether to walk the clobbering
1286/// access chain, or all the accesses.
1287///
1288/// Normally, MemoryDef are all just def/use linked together, so a def_chain on
1289/// a MemoryDef will walk all MemoryDefs above it in the program until it hits
1290/// a phi node. The optimized chain walks the clobbering access of a store.
1291/// So if you are just trying to find, given a store, what the next
1292/// thing that would clobber the same memory is, you want the optimized chain.
1293template <class T, bool UseOptimizedChain = false>
1294struct def_chain_iterator
1295 : public iterator_facade_base<def_chain_iterator<T, UseOptimizedChain>,
1296 std::forward_iterator_tag, MemoryAccess *> {
1297 def_chain_iterator() : MA(nullptr) {}
1298 def_chain_iterator(T MA) : MA(MA) {}
1299
1300 T operator*() const { return MA; }
1301
1302 def_chain_iterator &operator++() {
1303 // N.B. liveOnEntry has a null defining access.
1304 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1305 if (UseOptimizedChain && MUD->isOptimized())
1306 MA = MUD->getOptimized();
1307 else
1308 MA = MUD->getDefiningAccess();
1309 } else {
1310 MA = nullptr;
1311 }
1312
1313 return *this;
1314 }
1315
1316 bool operator==(const def_chain_iterator &O) const { return MA == O.MA; }
1317
1318private:
1319 T MA;
1320};
1321
1322template <class T>
1323inline iterator_range<def_chain_iterator<T>>
1324def_chain(T MA, MemoryAccess *UpTo = nullptr) {
1325#ifdef EXPENSIVE_CHECKS
1326 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-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Analysis/MemorySSA.h"
, 1327, __PRETTY_FUNCTION__))
1327 "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-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Analysis/MemorySSA.h"
, 1327, __PRETTY_FUNCTION__))
;
1328#endif
1329 return make_range(def_chain_iterator<T>(MA), def_chain_iterator<T>(UpTo));
1330}
1331
1332template <class T>
1333inline iterator_range<def_chain_iterator<T, true>> optimized_def_chain(T MA) {
1334 return make_range(def_chain_iterator<T, true>(MA),
1335 def_chain_iterator<T, true>(nullptr));
1336}
1337
1338} // end namespace llvm
1339
1340#endif // LLVM_ANALYSIS_MEMORYSSA_H