Bug Summary

File:llvm/lib/Analysis/MemorySSA.cpp
Warning:line 2020, 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 -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~++20210621111111+acefe0eaaf82/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~++20210621111111+acefe0eaaf82/build-llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/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-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/build-llvm/lib/Analysis -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82=. -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-06-21-164211-33944-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/lib/Analysis/MemorySSA.cpp

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

/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/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(AliasResult::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(
303 MemoryAccess *DMA, bool Optimized = false,
304 Optional<AliasResult> AR = AliasResult(AliasResult::MayAlias)) {
305 if (!Optimized) {
306 setOperand(0, DMA);
307 return;
308 }
309 setOptimized(DMA);
310 setOptimizedAccessType(AR);
311 }
312
313private:
314 Instruction *MemoryInstruction;
315 Optional<AliasResult> OptimizedAccessAlias;
316};
317
318/// Represents read-only accesses to memory
319///
320/// In particular, the set of Instructions that will be represented by
321/// MemoryUse's is exactly the set of Instructions for which
322/// AliasAnalysis::getModRefInfo returns "Ref".
323class MemoryUse final : public MemoryUseOrDef {
324public:
325 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
;
326
327 MemoryUse(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB)
328 : MemoryUseOrDef(C, DMA, MemoryUseVal, deleteMe, MI, BB,
329 /*NumOperands=*/1) {}
330
331 // allocate space for exactly one operand
332 void *operator new(size_t s) { return User::operator new(s, 1); }
333
334 static bool classof(const Value *MA) {
335 return MA->getValueID() == MemoryUseVal;
336 }
337
338 void print(raw_ostream &OS) const;
339
340 void setOptimized(MemoryAccess *DMA) {
341 OptimizedID = DMA->getID();
342 setOperand(0, DMA);
343 }
344
345 bool isOptimized() const {
346 return getDefiningAccess() && OptimizedID == getDefiningAccess()->getID();
347 }
348
349 MemoryAccess *getOptimized() const {
350 return getDefiningAccess();
351 }
352
353 void resetOptimized() {
354 OptimizedID = INVALID_MEMORYACCESS_ID;
355 }
356
357protected:
358 friend class MemorySSA;
359
360private:
361 static void deleteMe(DerivedUser *Self);
362
363 unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
364};
365
366template <>
367struct OperandTraits<MemoryUse> : public FixedNumOperandTraits<MemoryUse, 1> {};
368DEFINE_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 { (static_cast <bool
> (i_nocapture < OperandTraits<MemoryUse>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<MemoryUse>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 368, __extension__ __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
) { (static_cast <bool> (i_nocapture < OperandTraits
<MemoryUse>::operands(this) && "setOperand() out of range!"
) ? void (0) : __assert_fail ("i_nocapture < OperandTraits<MemoryUse>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 368, __extension__ __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); }
369
370/// Represents a read-write access to memory, whether it is a must-alias,
371/// or a may-alias.
372///
373/// In particular, the set of Instructions that will be represented by
374/// MemoryDef's is exactly the set of Instructions for which
375/// AliasAnalysis::getModRefInfo returns "Mod" or "ModRef".
376/// Note that, in order to provide def-def chains, all defs also have a use
377/// associated with them. This use points to the nearest reaching
378/// MemoryDef/MemoryPhi.
379class MemoryDef final : public MemoryUseOrDef {
380public:
381 friend class MemorySSA;
382
383 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
;
384
385 MemoryDef(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB,
386 unsigned Ver)
387 : MemoryUseOrDef(C, DMA, MemoryDefVal, deleteMe, MI, BB,
388 /*NumOperands=*/2),
389 ID(Ver) {}
390
391 // allocate space for exactly two operands
392 void *operator new(size_t s) { return User::operator new(s, 2); }
393
394 static bool classof(const Value *MA) {
395 return MA->getValueID() == MemoryDefVal;
396 }
397
398 void setOptimized(MemoryAccess *MA) {
399 setOperand(1, MA);
400 OptimizedID = MA->getID();
401 }
402
403 MemoryAccess *getOptimized() const {
404 return cast_or_null<MemoryAccess>(getOperand(1));
405 }
406
407 bool isOptimized() const {
408 return getOptimized() && OptimizedID == getOptimized()->getID();
409 }
410
411 void resetOptimized() {
412 OptimizedID = INVALID_MEMORYACCESS_ID;
413 setOperand(1, nullptr);
414 }
415
416 void print(raw_ostream &OS) const;
417
418 unsigned getID() const { return ID; }
419
420private:
421 static void deleteMe(DerivedUser *Self);
422
423 const unsigned ID;
424 unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
425};
426
427template <>
428struct OperandTraits<MemoryDef> : public FixedNumOperandTraits<MemoryDef, 2> {};
429DEFINE_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 { (static_cast <bool
> (i_nocapture < OperandTraits<MemoryDef>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<MemoryDef>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 429, __extension__ __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
) { (static_cast <bool> (i_nocapture < OperandTraits
<MemoryDef>::operands(this) && "setOperand() out of range!"
) ? void (0) : __assert_fail ("i_nocapture < OperandTraits<MemoryDef>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 429, __extension__ __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); }
430
431template <>
432struct OperandTraits<MemoryUseOrDef> {
433 static Use *op_begin(MemoryUseOrDef *MUD) {
434 if (auto *MU = dyn_cast<MemoryUse>(MUD))
435 return OperandTraits<MemoryUse>::op_begin(MU);
436 return OperandTraits<MemoryDef>::op_begin(cast<MemoryDef>(MUD));
437 }
438
439 static Use *op_end(MemoryUseOrDef *MUD) {
440 if (auto *MU = dyn_cast<MemoryUse>(MUD))
441 return OperandTraits<MemoryUse>::op_end(MU);
442 return OperandTraits<MemoryDef>::op_end(cast<MemoryDef>(MUD));
443 }
444
445 static unsigned operands(const MemoryUseOrDef *MUD) {
446 if (const auto *MU = dyn_cast<MemoryUse>(MUD))
447 return OperandTraits<MemoryUse>::operands(MU);
448 return OperandTraits<MemoryDef>::operands(cast<MemoryDef>(MUD));
449 }
450};
451DEFINE_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 { (static_cast <bool
> (i_nocapture < OperandTraits<MemoryUseOrDef>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<MemoryUseOrDef>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 451, __extension__ __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) { (static_cast <bool> (i_nocapture <
OperandTraits<MemoryUseOrDef>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<MemoryUseOrDef>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 451, __extension__ __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); }
452
453/// Represents phi nodes for memory accesses.
454///
455/// These have the same semantic as regular phi nodes, with the exception that
456/// only one phi will ever exist in a given basic block.
457/// Guaranteeing one phi per block means guaranteeing there is only ever one
458/// valid reaching MemoryDef/MemoryPHI along each path to the phi node.
459/// This is ensured by not allowing disambiguation of the RHS of a MemoryDef or
460/// a MemoryPhi's operands.
461/// That is, given
462/// if (a) {
463/// store %a
464/// store %b
465/// }
466/// it *must* be transformed into
467/// if (a) {
468/// 1 = MemoryDef(liveOnEntry)
469/// store %a
470/// 2 = MemoryDef(1)
471/// store %b
472/// }
473/// and *not*
474/// if (a) {
475/// 1 = MemoryDef(liveOnEntry)
476/// store %a
477/// 2 = MemoryDef(liveOnEntry)
478/// store %b
479/// }
480/// even if the two stores do not conflict. Otherwise, both 1 and 2 reach the
481/// end of the branch, and if there are not two phi nodes, one will be
482/// disconnected completely from the SSA graph below that point.
483/// Because MemoryUse's do not generate new definitions, they do not have this
484/// issue.
485class MemoryPhi final : public MemoryAccess {
486 // allocate space for exactly zero operands
487 void *operator new(size_t s) { return User::operator new(s); }
488
489public:
490 /// Provide fast operand accessors
491 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
;
492
493 MemoryPhi(LLVMContext &C, BasicBlock *BB, unsigned Ver, unsigned NumPreds = 0)
494 : MemoryAccess(C, MemoryPhiVal, deleteMe, BB, 0), ID(Ver),
495 ReservedSpace(NumPreds) {
496 allocHungoffUses(ReservedSpace);
497 }
498
499 // Block iterator interface. This provides access to the list of incoming
500 // basic blocks, which parallels the list of incoming values.
501 using block_iterator = BasicBlock **;
502 using const_block_iterator = BasicBlock *const *;
503
504 block_iterator block_begin() {
505 return reinterpret_cast<block_iterator>(op_begin() + ReservedSpace);
506 }
507
508 const_block_iterator block_begin() const {
509 return reinterpret_cast<const_block_iterator>(op_begin() + ReservedSpace);
510 }
511
512 block_iterator block_end() { return block_begin() + getNumOperands(); }
513
514 const_block_iterator block_end() const {
515 return block_begin() + getNumOperands();
516 }
517
518 iterator_range<block_iterator> blocks() {
519 return make_range(block_begin(), block_end());
520 }
521
522 iterator_range<const_block_iterator> blocks() const {
523 return make_range(block_begin(), block_end());
524 }
525
526 op_range incoming_values() { return operands(); }
527
528 const_op_range incoming_values() const { return operands(); }
529
530 /// Return the number of incoming edges
531 unsigned getNumIncomingValues() const { return getNumOperands(); }
532
533 /// Return incoming value number x
534 MemoryAccess *getIncomingValue(unsigned I) const { return getOperand(I); }
535 void setIncomingValue(unsigned I, MemoryAccess *V) {
536 assert(V && "PHI node got a null value!")(static_cast <bool> (V && "PHI node got a null value!"
) ? void (0) : __assert_fail ("V && \"PHI node got a null value!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 536, __extension__ __PRETTY_FUNCTION__))
;
537 setOperand(I, V);
538 }
539
540 static unsigned getOperandNumForIncomingValue(unsigned I) { return I; }
541 static unsigned getIncomingValueNumForOperand(unsigned I) { return I; }
542
543 /// Return incoming basic block number @p i.
544 BasicBlock *getIncomingBlock(unsigned I) const { return block_begin()[I]; }
545
546 /// Return incoming basic block corresponding
547 /// to an operand of the PHI.
548 BasicBlock *getIncomingBlock(const Use &U) const {
549 assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?")(static_cast <bool> (this == U.getUser() && "Iterator doesn't point to PHI's Uses?"
) ? void (0) : __assert_fail ("this == U.getUser() && \"Iterator doesn't point to PHI's Uses?\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 549, __extension__ __PRETTY_FUNCTION__))
;
550 return getIncomingBlock(unsigned(&U - op_begin()));
551 }
552
553 /// Return incoming basic block corresponding
554 /// to value use iterator.
555 BasicBlock *getIncomingBlock(MemoryAccess::const_user_iterator I) const {
556 return getIncomingBlock(I.getUse());
557 }
558
559 void setIncomingBlock(unsigned I, BasicBlock *BB) {
560 assert(BB && "PHI node got a null basic block!")(static_cast <bool> (BB && "PHI node got a null basic block!"
) ? void (0) : __assert_fail ("BB && \"PHI node got a null basic block!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 560, __extension__ __PRETTY_FUNCTION__))
;
561 block_begin()[I] = BB;
562 }
563
564 /// Add an incoming value to the end of the PHI list
565 void addIncoming(MemoryAccess *V, BasicBlock *BB) {
566 if (getNumOperands() == ReservedSpace)
567 growOperands(); // Get more space!
568 // Initialize some new operands.
569 setNumHungOffUseOperands(getNumOperands() + 1);
570 setIncomingValue(getNumOperands() - 1, V);
571 setIncomingBlock(getNumOperands() - 1, BB);
572 }
573
574 /// Return the first index of the specified basic
575 /// block in the value list for this PHI. Returns -1 if no instance.
576 int getBasicBlockIndex(const BasicBlock *BB) const {
577 for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
578 if (block_begin()[I] == BB)
579 return I;
580 return -1;
581 }
582
583 MemoryAccess *getIncomingValueForBlock(const BasicBlock *BB) const {
584 int Idx = getBasicBlockIndex(BB);
585 assert(Idx >= 0 && "Invalid basic block argument!")(static_cast <bool> (Idx >= 0 && "Invalid basic block argument!"
) ? void (0) : __assert_fail ("Idx >= 0 && \"Invalid basic block argument!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 585, __extension__ __PRETTY_FUNCTION__))
;
586 return getIncomingValue(Idx);
587 }
588
589 // After deleting incoming position I, the order of incoming may be changed.
590 void unorderedDeleteIncoming(unsigned I) {
591 unsigned E = getNumOperands();
592 assert(I < E && "Cannot remove out of bounds Phi entry.")(static_cast <bool> (I < E && "Cannot remove out of bounds Phi entry."
) ? void (0) : __assert_fail ("I < E && \"Cannot remove out of bounds Phi entry.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 592, __extension__ __PRETTY_FUNCTION__))
;
593 // MemoryPhi must have at least two incoming values, otherwise the MemoryPhi
594 // itself should be deleted.
595 assert(E >= 2 && "Cannot only remove incoming values in MemoryPhis with "(static_cast <bool> (E >= 2 && "Cannot only remove incoming values in MemoryPhis with "
"at least 2 values.") ? void (0) : __assert_fail ("E >= 2 && \"Cannot only remove incoming values in MemoryPhis with \" \"at least 2 values.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 596, __extension__ __PRETTY_FUNCTION__))
596 "at least 2 values.")(static_cast <bool> (E >= 2 && "Cannot only remove incoming values in MemoryPhis with "
"at least 2 values.") ? void (0) : __assert_fail ("E >= 2 && \"Cannot only remove incoming values in MemoryPhis with \" \"at least 2 values.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 596, __extension__ __PRETTY_FUNCTION__))
;
597 setIncomingValue(I, getIncomingValue(E - 1));
598 setIncomingBlock(I, block_begin()[E - 1]);
599 setOperand(E - 1, nullptr);
600 block_begin()[E - 1] = nullptr;
601 setNumHungOffUseOperands(getNumOperands() - 1);
602 }
603
604 // After deleting entries that satisfy Pred, remaining entries may have
605 // changed order.
606 template <typename Fn> void unorderedDeleteIncomingIf(Fn &&Pred) {
607 for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
608 if (Pred(getIncomingValue(I), getIncomingBlock(I))) {
609 unorderedDeleteIncoming(I);
610 E = getNumOperands();
611 --I;
612 }
613 assert(getNumOperands() >= 1 &&(static_cast <bool> (getNumOperands() >= 1 &&
"Cannot remove all incoming blocks in a MemoryPhi.") ? void (
0) : __assert_fail ("getNumOperands() >= 1 && \"Cannot remove all incoming blocks in a MemoryPhi.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 614, __extension__ __PRETTY_FUNCTION__))
614 "Cannot remove all incoming blocks in a MemoryPhi.")(static_cast <bool> (getNumOperands() >= 1 &&
"Cannot remove all incoming blocks in a MemoryPhi.") ? void (
0) : __assert_fail ("getNumOperands() >= 1 && \"Cannot remove all incoming blocks in a MemoryPhi.\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 614, __extension__ __PRETTY_FUNCTION__))
;
615 }
616
617 // After deleting incoming block BB, the incoming blocks order may be changed.
618 void unorderedDeleteIncomingBlock(const BasicBlock *BB) {
619 unorderedDeleteIncomingIf(
620 [&](const MemoryAccess *, const BasicBlock *B) { return BB == B; });
621 }
622
623 // After deleting incoming memory access MA, the incoming accesses order may
624 // be changed.
625 void unorderedDeleteIncomingValue(const MemoryAccess *MA) {
626 unorderedDeleteIncomingIf(
627 [&](const MemoryAccess *M, const BasicBlock *) { return MA == M; });
628 }
629
630 static bool classof(const Value *V) {
631 return V->getValueID() == MemoryPhiVal;
632 }
633
634 void print(raw_ostream &OS) const;
635
636 unsigned getID() const { return ID; }
637
638protected:
639 friend class MemorySSA;
640
641 /// this is more complicated than the generic
642 /// User::allocHungoffUses, because we have to allocate Uses for the incoming
643 /// values and pointers to the incoming blocks, all in one allocation.
644 void allocHungoffUses(unsigned N) {
645 User::allocHungoffUses(N, /* IsPhi */ true);
646 }
647
648private:
649 // For debugging only
650 const unsigned ID;
651 unsigned ReservedSpace;
652
653 /// This grows the operand list in response to a push_back style of
654 /// operation. This grows the number of ops by 1.5 times.
655 void growOperands() {
656 unsigned E = getNumOperands();
657 // 2 op PHI nodes are VERY common, so reserve at least enough for that.
658 ReservedSpace = std::max(E + E / 2, 2u);
659 growHungoffUses(ReservedSpace, /* IsPhi */ true);
660 }
661
662 static void deleteMe(DerivedUser *Self);
663};
664
665inline unsigned MemoryAccess::getID() const {
666 assert((isa<MemoryDef>(this) || isa<MemoryPhi>(this)) &&(static_cast <bool> ((isa<MemoryDef>(this) || isa
<MemoryPhi>(this)) && "only memory defs and phis have ids"
) ? void (0) : __assert_fail ("(isa<MemoryDef>(this) || isa<MemoryPhi>(this)) && \"only memory defs and phis have ids\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 667, __extension__ __PRETTY_FUNCTION__))
667 "only memory defs and phis have ids")(static_cast <bool> ((isa<MemoryDef>(this) || isa
<MemoryPhi>(this)) && "only memory defs and phis have ids"
) ? void (0) : __assert_fail ("(isa<MemoryDef>(this) || isa<MemoryPhi>(this)) && \"only memory defs and phis have ids\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 667, __extension__ __PRETTY_FUNCTION__))
;
668 if (const auto *MD = dyn_cast<MemoryDef>(this))
669 return MD->getID();
670 return cast<MemoryPhi>(this)->getID();
671}
672
673inline bool MemoryUseOrDef::isOptimized() const {
674 if (const auto *MD = dyn_cast<MemoryDef>(this))
675 return MD->isOptimized();
676 return cast<MemoryUse>(this)->isOptimized();
677}
678
679inline MemoryAccess *MemoryUseOrDef::getOptimized() const {
680 if (const auto *MD = dyn_cast<MemoryDef>(this))
681 return MD->getOptimized();
682 return cast<MemoryUse>(this)->getOptimized();
683}
684
685inline void MemoryUseOrDef::setOptimized(MemoryAccess *MA) {
686 if (auto *MD = dyn_cast<MemoryDef>(this))
687 MD->setOptimized(MA);
688 else
689 cast<MemoryUse>(this)->setOptimized(MA);
690}
691
692inline void MemoryUseOrDef::resetOptimized() {
693 if (auto *MD = dyn_cast<MemoryDef>(this))
694 MD->resetOptimized();
695 else
696 cast<MemoryUse>(this)->resetOptimized();
697}
698
699template <> struct OperandTraits<MemoryPhi> : public HungoffOperandTraits<2> {};
700DEFINE_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 { (static_cast <bool
> (i_nocapture < OperandTraits<MemoryPhi>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<MemoryPhi>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 700, __extension__ __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
) { (static_cast <bool> (i_nocapture < OperandTraits
<MemoryPhi>::operands(this) && "setOperand() out of range!"
) ? void (0) : __assert_fail ("i_nocapture < OperandTraits<MemoryPhi>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 700, __extension__ __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); }
701
702/// Encapsulates MemorySSA, including all data associated with memory
703/// accesses.
704class MemorySSA {
705public:
706 MemorySSA(Function &, AliasAnalysis *, DominatorTree *);
707
708 // MemorySSA must remain where it's constructed; Walkers it creates store
709 // pointers to it.
710 MemorySSA(MemorySSA &&) = delete;
711
712 ~MemorySSA();
713
714 MemorySSAWalker *getWalker();
715 MemorySSAWalker *getSkipSelfWalker();
716
717 /// Given a memory Mod/Ref'ing instruction, get the MemorySSA
718 /// access associated with it. If passed a basic block gets the memory phi
719 /// node that exists for that block, if there is one. Otherwise, this will get
720 /// a MemoryUseOrDef.
721 MemoryUseOrDef *getMemoryAccess(const Instruction *I) const {
722 return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I));
723 }
724
725 MemoryPhi *getMemoryAccess(const BasicBlock *BB) const {
726 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
727 }
728
729 DominatorTree &getDomTree() const { return *DT; }
730
731 void dump() const;
732 void print(raw_ostream &) const;
733
734 /// Return true if \p MA represents the live on entry value
735 ///
736 /// Loads and stores from pointer arguments and other global values may be
737 /// defined by memory operations that do not occur in the current function, so
738 /// they may be live on entry to the function. MemorySSA represents such
739 /// memory state by the live on entry definition, which is guaranteed to occur
740 /// before any other memory access in the function.
741 inline bool isLiveOnEntryDef(const MemoryAccess *MA) const {
742 return MA == LiveOnEntryDef.get();
743 }
744
745 inline MemoryAccess *getLiveOnEntryDef() const {
746 return LiveOnEntryDef.get();
747 }
748
749 // Sadly, iplists, by default, owns and deletes pointers added to the
750 // list. It's not currently possible to have two iplists for the same type,
751 // where one owns the pointers, and one does not. This is because the traits
752 // are per-type, not per-tag. If this ever changes, we should make the
753 // DefList an iplist.
754 using AccessList = iplist<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>;
755 using DefsList =
756 simple_ilist<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>>;
757
758 /// Return the list of MemoryAccess's for a given basic block.
759 ///
760 /// This list is not modifiable by the user.
761 const AccessList *getBlockAccesses(const BasicBlock *BB) const {
762 return getWritableBlockAccesses(BB);
6
Calling 'MemorySSA::getWritableBlockAccesses'
10
Returning from 'MemorySSA::getWritableBlockAccesses'
11
Returning pointer, which participates in a condition later
12
Returning pointer
763 }
764
765 /// Return the list of MemoryDef's and MemoryPhi's for a given basic
766 /// block.
767 ///
768 /// This list is not modifiable by the user.
769 const DefsList *getBlockDefs(const BasicBlock *BB) const {
770 return getWritableBlockDefs(BB);
16
Calling 'MemorySSA::getWritableBlockDefs'
19
Returning from 'MemorySSA::getWritableBlockDefs'
20
Returning pointer, which participates in a condition later
771 }
772
773 /// Given two memory accesses in the same basic block, determine
774 /// whether MemoryAccess \p A dominates MemoryAccess \p B.
775 bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const;
776
777 /// Given two memory accesses in potentially different blocks,
778 /// determine whether MemoryAccess \p A dominates MemoryAccess \p B.
779 bool dominates(const MemoryAccess *A, const MemoryAccess *B) const;
780
781 /// Given a MemoryAccess and a Use, determine whether MemoryAccess \p A
782 /// dominates Use \p B.
783 bool dominates(const MemoryAccess *A, const Use &B) const;
784
785 /// Verify that MemorySSA is self consistent (IE definitions dominate
786 /// all uses, uses appear in the right places). This is used by unit tests.
787 void verifyMemorySSA() const;
788
789 /// Used in various insertion functions to specify whether we are talking
790 /// about the beginning or end of a block.
791 enum InsertionPlace { Beginning, End, BeforeTerminator };
792
793protected:
794 // Used by Memory SSA annotater, dumpers, and wrapper pass
795 friend class MemorySSAAnnotatedWriter;
796 friend class MemorySSAPrinterLegacyPass;
797 friend class MemorySSAUpdater;
798
799 void verifyOrderingDominationAndDefUses(Function &F) const;
800 void verifyDominationNumbers(const Function &F) const;
801 void verifyPrevDefInPhis(Function &F) const;
802
803 // This is used by the use optimizer and updater.
804 AccessList *getWritableBlockAccesses(const BasicBlock *BB) const {
805 auto It = PerBlockAccesses.find(BB);
806 return It == PerBlockAccesses.end() ? nullptr : It->second.get();
7
'?' condition is false
8
Returning pointer, which participates in a condition later
9
Returning pointer
807 }
808
809 // This is used by the use optimizer and updater.
810 DefsList *getWritableBlockDefs(const BasicBlock *BB) const {
811 auto It = PerBlockDefs.find(BB);
812 return It == PerBlockDefs.end() ? nullptr : It->second.get();
17
'?' condition is false
18
Returning pointer, which participates in a condition later
813 }
814
815 // These is used by the updater to perform various internal MemorySSA
816 // machinsations. They do not always leave the IR in a correct state, and
817 // relies on the updater to fixup what it breaks, so it is not public.
818
819 void moveTo(MemoryUseOrDef *What, BasicBlock *BB, AccessList::iterator Where);
820 void moveTo(MemoryAccess *What, BasicBlock *BB, InsertionPlace Point);
821
822 // Rename the dominator tree branch rooted at BB.
823 void renamePass(BasicBlock *BB, MemoryAccess *IncomingVal,
824 SmallPtrSetImpl<BasicBlock *> &Visited) {
825 renamePass(DT->getNode(BB), IncomingVal, Visited, true, true);
826 }
827
828 void removeFromLookups(MemoryAccess *);
829 void removeFromLists(MemoryAccess *, bool ShouldDelete = true);
830 void insertIntoListsForBlock(MemoryAccess *, const BasicBlock *,
831 InsertionPlace);
832 void insertIntoListsBefore(MemoryAccess *, const BasicBlock *,
833 AccessList::iterator);
834 MemoryUseOrDef *createDefinedAccess(Instruction *, MemoryAccess *,
835 const MemoryUseOrDef *Template = nullptr,
836 bool CreationMustSucceed = true);
837
838private:
839 template <class AliasAnalysisType> class ClobberWalkerBase;
840 template <class AliasAnalysisType> class CachingWalker;
841 template <class AliasAnalysisType> class SkipSelfWalker;
842 class OptimizeUses;
843
844 CachingWalker<AliasAnalysis> *getWalkerImpl();
845 void buildMemorySSA(BatchAAResults &BAA);
846
847 void prepareForMoveTo(MemoryAccess *, BasicBlock *);
848 void verifyUseInDefs(MemoryAccess *, MemoryAccess *) const;
849
850 using AccessMap = DenseMap<const BasicBlock *, std::unique_ptr<AccessList>>;
851 using DefsMap = DenseMap<const BasicBlock *, std::unique_ptr<DefsList>>;
852
853 void markUnreachableAsLiveOnEntry(BasicBlock *BB);
854 MemoryPhi *createMemoryPhi(BasicBlock *BB);
855 template <typename AliasAnalysisType>
856 MemoryUseOrDef *createNewAccess(Instruction *, AliasAnalysisType *,
857 const MemoryUseOrDef *Template = nullptr);
858 void placePHINodes(const SmallPtrSetImpl<BasicBlock *> &);
859 MemoryAccess *renameBlock(BasicBlock *, MemoryAccess *, bool);
860 void renameSuccessorPhis(BasicBlock *, MemoryAccess *, bool);
861 void renamePass(DomTreeNode *, MemoryAccess *IncomingVal,
862 SmallPtrSetImpl<BasicBlock *> &Visited,
863 bool SkipVisited = false, bool RenameAllUses = false);
864 AccessList *getOrCreateAccessList(const BasicBlock *);
865 DefsList *getOrCreateDefsList(const BasicBlock *);
866 void renumberBlock(const BasicBlock *) const;
867 AliasAnalysis *AA;
868 DominatorTree *DT;
869 Function &F;
870
871 // Memory SSA mappings
872 DenseMap<const Value *, MemoryAccess *> ValueToMemoryAccess;
873
874 // These two mappings contain the main block to access/def mappings for
875 // MemorySSA. The list contained in PerBlockAccesses really owns all the
876 // MemoryAccesses.
877 // Both maps maintain the invariant that if a block is found in them, the
878 // corresponding list is not empty, and if a block is not found in them, the
879 // corresponding list is empty.
880 AccessMap PerBlockAccesses;
881 DefsMap PerBlockDefs;
882 std::unique_ptr<MemoryAccess, ValueDeleter> LiveOnEntryDef;
883
884 // Domination mappings
885 // Note that the numbering is local to a block, even though the map is
886 // global.
887 mutable SmallPtrSet<const BasicBlock *, 16> BlockNumberingValid;
888 mutable DenseMap<const MemoryAccess *, unsigned long> BlockNumbering;
889
890 // Memory SSA building info
891 std::unique_ptr<ClobberWalkerBase<AliasAnalysis>> WalkerBase;
892 std::unique_ptr<CachingWalker<AliasAnalysis>> Walker;
893 std::unique_ptr<SkipSelfWalker<AliasAnalysis>> SkipWalker;
894 unsigned NextID;
895};
896
897// Internal MemorySSA utils, for use by MemorySSA classes and walkers
898class MemorySSAUtil {
899protected:
900 friend class GVNHoist;
901 friend class MemorySSAWalker;
902
903 // This function should not be used by new passes.
904 static bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
905 AliasAnalysis &AA);
906};
907
908// This pass does eager building and then printing of MemorySSA. It is used by
909// the tests to be able to build, dump, and verify Memory SSA.
910class MemorySSAPrinterLegacyPass : public FunctionPass {
911public:
912 MemorySSAPrinterLegacyPass();
913
914 bool runOnFunction(Function &) override;
915 void getAnalysisUsage(AnalysisUsage &AU) const override;
916
917 static char ID;
918};
919
920/// An analysis that produces \c MemorySSA for a function.
921///
922class MemorySSAAnalysis : public AnalysisInfoMixin<MemorySSAAnalysis> {
923 friend AnalysisInfoMixin<MemorySSAAnalysis>;
924
925 static AnalysisKey Key;
926
927public:
928 // Wrap MemorySSA result to ensure address stability of internal MemorySSA
929 // pointers after construction. Use a wrapper class instead of plain
930 // unique_ptr<MemorySSA> to avoid build breakage on MSVC.
931 struct Result {
932 Result(std::unique_ptr<MemorySSA> &&MSSA) : MSSA(std::move(MSSA)) {}
933
934 MemorySSA &getMSSA() { return *MSSA.get(); }
935
936 std::unique_ptr<MemorySSA> MSSA;
937
938 bool invalidate(Function &F, const PreservedAnalyses &PA,
939 FunctionAnalysisManager::Invalidator &Inv);
940 };
941
942 Result run(Function &F, FunctionAnalysisManager &AM);
943};
944
945/// Printer pass for \c MemorySSA.
946class MemorySSAPrinterPass : public PassInfoMixin<MemorySSAPrinterPass> {
947 raw_ostream &OS;
948
949public:
950 explicit MemorySSAPrinterPass(raw_ostream &OS) : OS(OS) {}
951
952 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
953};
954
955/// Verifier pass for \c MemorySSA.
956struct MemorySSAVerifierPass : PassInfoMixin<MemorySSAVerifierPass> {
957 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
958};
959
960/// Legacy analysis pass which computes \c MemorySSA.
961class MemorySSAWrapperPass : public FunctionPass {
962public:
963 MemorySSAWrapperPass();
964
965 static char ID;
966
967 bool runOnFunction(Function &) override;
968 void releaseMemory() override;
969 MemorySSA &getMSSA() { return *MSSA; }
970 const MemorySSA &getMSSA() const { return *MSSA; }
971
972 void getAnalysisUsage(AnalysisUsage &AU) const override;
973
974 void verifyAnalysis() const override;
975 void print(raw_ostream &OS, const Module *M = nullptr) const override;
976
977private:
978 std::unique_ptr<MemorySSA> MSSA;
979};
980
981/// This is the generic walker interface for walkers of MemorySSA.
982/// Walkers are used to be able to further disambiguate the def-use chains
983/// MemorySSA gives you, or otherwise produce better info than MemorySSA gives
984/// you.
985/// In particular, while the def-use chains provide basic information, and are
986/// guaranteed to give, for example, the nearest may-aliasing MemoryDef for a
987/// MemoryUse as AliasAnalysis considers it, a user mant want better or other
988/// information. In particular, they may want to use SCEV info to further
989/// disambiguate memory accesses, or they may want the nearest dominating
990/// may-aliasing MemoryDef for a call or a store. This API enables a
991/// standardized interface to getting and using that info.
992class MemorySSAWalker {
993public:
994 MemorySSAWalker(MemorySSA *);
995 virtual ~MemorySSAWalker() = default;
996
997 using MemoryAccessSet = SmallVector<MemoryAccess *, 8>;
998
999 /// Given a memory Mod/Ref/ModRef'ing instruction, calling this
1000 /// will give you the nearest dominating MemoryAccess that Mod's the location
1001 /// the instruction accesses (by skipping any def which AA can prove does not
1002 /// alias the location(s) accessed by the instruction given).
1003 ///
1004 /// Note that this will return a single access, and it must dominate the
1005 /// Instruction, so if an operand of a MemoryPhi node Mod's the instruction,
1006 /// this will return the MemoryPhi, not the operand. This means that
1007 /// given:
1008 /// if (a) {
1009 /// 1 = MemoryDef(liveOnEntry)
1010 /// store %a
1011 /// } else {
1012 /// 2 = MemoryDef(liveOnEntry)
1013 /// store %b
1014 /// }
1015 /// 3 = MemoryPhi(2, 1)
1016 /// MemoryUse(3)
1017 /// load %a
1018 ///
1019 /// calling this API on load(%a) will return the MemoryPhi, not the MemoryDef
1020 /// in the if (a) branch.
1021 MemoryAccess *getClobberingMemoryAccess(const Instruction *I) {
1022 MemoryAccess *MA = MSSA->getMemoryAccess(I);
1023 assert(MA && "Handed an instruction that MemorySSA doesn't recognize?")(static_cast <bool> (MA && "Handed an instruction that MemorySSA doesn't recognize?"
) ? void (0) : __assert_fail ("MA && \"Handed an instruction that MemorySSA doesn't recognize?\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 1023, __extension__ __PRETTY_FUNCTION__))
;
1024 return getClobberingMemoryAccess(MA);
1025 }
1026
1027 /// Does the same thing as getClobberingMemoryAccess(const Instruction *I),
1028 /// but takes a MemoryAccess instead of an Instruction.
1029 virtual MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) = 0;
1030
1031 /// Given a potentially clobbering memory access and a new location,
1032 /// calling this will give you the nearest dominating clobbering MemoryAccess
1033 /// (by skipping non-aliasing def links).
1034 ///
1035 /// This version of the function is mainly used to disambiguate phi translated
1036 /// pointers, where the value of a pointer may have changed from the initial
1037 /// memory access. Note that this expects to be handed either a MemoryUse,
1038 /// or an already potentially clobbering access. Unlike the above API, if
1039 /// given a MemoryDef that clobbers the pointer as the starting access, it
1040 /// will return that MemoryDef, whereas the above would return the clobber
1041 /// starting from the use side of the memory def.
1042 virtual MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
1043 const MemoryLocation &) = 0;
1044
1045 /// Given a memory access, invalidate anything this walker knows about
1046 /// that access.
1047 /// This API is used by walkers that store information to perform basic cache
1048 /// invalidation. This will be called by MemorySSA at appropriate times for
1049 /// the walker it uses or returns.
1050 virtual void invalidateInfo(MemoryAccess *) {}
1051
1052protected:
1053 friend class MemorySSA; // For updating MSSA pointer in MemorySSA move
1054 // constructor.
1055 MemorySSA *MSSA;
1056};
1057
1058/// A MemorySSAWalker that does no alias queries, or anything else. It
1059/// simply returns the links as they were constructed by the builder.
1060class DoNothingMemorySSAWalker final : public MemorySSAWalker {
1061public:
1062 // Keep the overrides below from hiding the Instruction overload of
1063 // getClobberingMemoryAccess.
1064 using MemorySSAWalker::getClobberingMemoryAccess;
1065
1066 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override;
1067 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
1068 const MemoryLocation &) override;
1069};
1070
1071using MemoryAccessPair = std::pair<MemoryAccess *, MemoryLocation>;
1072using ConstMemoryAccessPair = std::pair<const MemoryAccess *, MemoryLocation>;
1073
1074/// Iterator base class used to implement const and non-const iterators
1075/// over the defining accesses of a MemoryAccess.
1076template <class T>
1077class memoryaccess_def_iterator_base
1078 : public iterator_facade_base<memoryaccess_def_iterator_base<T>,
1079 std::forward_iterator_tag, T, ptrdiff_t, T *,
1080 T *> {
1081 using BaseT = typename memoryaccess_def_iterator_base::iterator_facade_base;
1082
1083public:
1084 memoryaccess_def_iterator_base(T *Start) : Access(Start) {}
1085 memoryaccess_def_iterator_base() = default;
1086
1087 bool operator==(const memoryaccess_def_iterator_base &Other) const {
1088 return Access == Other.Access && (!Access || ArgNo == Other.ArgNo);
1089 }
1090
1091 // This is a bit ugly, but for MemoryPHI's, unlike PHINodes, you can't get the
1092 // block from the operand in constant time (In a PHINode, the uselist has
1093 // both, so it's just subtraction). We provide it as part of the
1094 // iterator to avoid callers having to linear walk to get the block.
1095 // If the operation becomes constant time on MemoryPHI's, this bit of
1096 // abstraction breaking should be removed.
1097 BasicBlock *getPhiArgBlock() const {
1098 MemoryPhi *MP = dyn_cast<MemoryPhi>(Access);
1099 assert(MP && "Tried to get phi arg block when not iterating over a PHI")(static_cast <bool> (MP && "Tried to get phi arg block when not iterating over a PHI"
) ? void (0) : __assert_fail ("MP && \"Tried to get phi arg block when not iterating over a PHI\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 1099, __extension__ __PRETTY_FUNCTION__))
;
1100 return MP->getIncomingBlock(ArgNo);
1101 }
1102
1103 typename std::iterator_traits<BaseT>::pointer operator*() const {
1104 assert(Access && "Tried to access past the end of our iterator")(static_cast <bool> (Access && "Tried to access past the end of our iterator"
) ? void (0) : __assert_fail ("Access && \"Tried to access past the end of our iterator\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 1104, __extension__ __PRETTY_FUNCTION__))
;
1105 // Go to the first argument for phis, and the defining access for everything
1106 // else.
1107 if (const MemoryPhi *MP = dyn_cast<MemoryPhi>(Access))
1108 return MP->getIncomingValue(ArgNo);
1109 return cast<MemoryUseOrDef>(Access)->getDefiningAccess();
1110 }
1111
1112 using BaseT::operator++;
1113 memoryaccess_def_iterator_base &operator++() {
1114 assert(Access && "Hit end of iterator")(static_cast <bool> (Access && "Hit end of iterator"
) ? void (0) : __assert_fail ("Access && \"Hit end of iterator\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 1114, __extension__ __PRETTY_FUNCTION__))
;
1115 if (const MemoryPhi *MP = dyn_cast<MemoryPhi>(Access)) {
1116 if (++ArgNo >= MP->getNumIncomingValues()) {
1117 ArgNo = 0;
1118 Access = nullptr;
1119 }
1120 } else {
1121 Access = nullptr;
1122 }
1123 return *this;
1124 }
1125
1126private:
1127 T *Access = nullptr;
1128 unsigned ArgNo = 0;
1129};
1130
1131inline memoryaccess_def_iterator MemoryAccess::defs_begin() {
1132 return memoryaccess_def_iterator(this);
1133}
1134
1135inline const_memoryaccess_def_iterator MemoryAccess::defs_begin() const {
1136 return const_memoryaccess_def_iterator(this);
1137}
1138
1139inline memoryaccess_def_iterator MemoryAccess::defs_end() {
1140 return memoryaccess_def_iterator();
1141}
1142
1143inline const_memoryaccess_def_iterator MemoryAccess::defs_end() const {
1144 return const_memoryaccess_def_iterator();
1145}
1146
1147/// GraphTraits for a MemoryAccess, which walks defs in the normal case,
1148/// and uses in the inverse case.
1149template <> struct GraphTraits<MemoryAccess *> {
1150 using NodeRef = MemoryAccess *;
1151 using ChildIteratorType = memoryaccess_def_iterator;
1152
1153 static NodeRef getEntryNode(NodeRef N) { return N; }
1154 static ChildIteratorType child_begin(NodeRef N) { return N->defs_begin(); }
1155 static ChildIteratorType child_end(NodeRef N) { return N->defs_end(); }
1156};
1157
1158template <> struct GraphTraits<Inverse<MemoryAccess *>> {
1159 using NodeRef = MemoryAccess *;
1160 using ChildIteratorType = MemoryAccess::iterator;
1161
1162 static NodeRef getEntryNode(NodeRef N) { return N; }
1163 static ChildIteratorType child_begin(NodeRef N) { return N->user_begin(); }
1164 static ChildIteratorType child_end(NodeRef N) { return N->user_end(); }
1165};
1166
1167/// Provide an iterator that walks defs, giving both the memory access,
1168/// and the current pointer location, updating the pointer location as it
1169/// changes due to phi node translation.
1170///
1171/// This iterator, while somewhat specialized, is what most clients actually
1172/// want when walking upwards through MemorySSA def chains. It takes a pair of
1173/// <MemoryAccess,MemoryLocation>, and walks defs, properly translating the
1174/// memory location through phi nodes for the user.
1175class upward_defs_iterator
1176 : public iterator_facade_base<upward_defs_iterator,
1177 std::forward_iterator_tag,
1178 const MemoryAccessPair> {
1179 using BaseT = upward_defs_iterator::iterator_facade_base;
1180
1181public:
1182 upward_defs_iterator(const MemoryAccessPair &Info, DominatorTree *DT,
1183 bool *PerformedPhiTranslation = nullptr)
1184 : DefIterator(Info.first), Location(Info.second),
1185 OriginalAccess(Info.first), DT(DT),
1186 PerformedPhiTranslation(PerformedPhiTranslation) {
1187 CurrentPair.first = nullptr;
1188
1189 WalkingPhi = Info.first && isa<MemoryPhi>(Info.first);
1190 fillInCurrentPair();
1191 }
1192
1193 upward_defs_iterator() { CurrentPair.first = nullptr; }
1194
1195 bool operator==(const upward_defs_iterator &Other) const {
1196 return DefIterator == Other.DefIterator;
1197 }
1198
1199 typename std::iterator_traits<BaseT>::reference operator*() const {
1200 assert(DefIterator != OriginalAccess->defs_end() &&(static_cast <bool> (DefIterator != OriginalAccess->
defs_end() && "Tried to access past the end of our iterator"
) ? void (0) : __assert_fail ("DefIterator != OriginalAccess->defs_end() && \"Tried to access past the end of our iterator\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 1201, __extension__ __PRETTY_FUNCTION__))
1201 "Tried to access past the end of our iterator")(static_cast <bool> (DefIterator != OriginalAccess->
defs_end() && "Tried to access past the end of our iterator"
) ? void (0) : __assert_fail ("DefIterator != OriginalAccess->defs_end() && \"Tried to access past the end of our iterator\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 1201, __extension__ __PRETTY_FUNCTION__))
;
1202 return CurrentPair;
1203 }
1204
1205 using BaseT::operator++;
1206 upward_defs_iterator &operator++() {
1207 assert(DefIterator != OriginalAccess->defs_end() &&(static_cast <bool> (DefIterator != OriginalAccess->
defs_end() && "Tried to access past the end of the iterator"
) ? void (0) : __assert_fail ("DefIterator != OriginalAccess->defs_end() && \"Tried to access past the end of the iterator\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 1208, __extension__ __PRETTY_FUNCTION__))
1208 "Tried to access past the end of the iterator")(static_cast <bool> (DefIterator != OriginalAccess->
defs_end() && "Tried to access past the end of the iterator"
) ? void (0) : __assert_fail ("DefIterator != OriginalAccess->defs_end() && \"Tried to access past the end of the iterator\""
, "/build/llvm-toolchain-snapshot-13~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 1208, __extension__ __PRETTY_FUNCTION__))
;
1209 ++DefIterator;
1210 if (DefIterator != OriginalAccess->defs_end())
1211 fillInCurrentPair();
1212 return *this;
1213 }
1214
1215 BasicBlock *getPhiArgBlock() const { return DefIterator.getPhiArgBlock(); }
1216
1217private:
1218 /// Returns true if \p Ptr is guaranteed to be loop invariant for any possible
1219 /// loop. In particular, this guarantees that it only references a single
1220 /// MemoryLocation during execution of the containing function.
1221 bool IsGuaranteedLoopInvariant(Value *Ptr) const;
1222
1223 void fillInCurrentPair() {
1224 CurrentPair.first = *DefIterator;
1225 CurrentPair.second = Location;
1226 if (WalkingPhi && Location.Ptr) {
1227 // Mark size as unknown, if the location is not guaranteed to be
1228 // loop-invariant for any possible loop in the function. Setting the size
1229 // to unknown guarantees that any memory accesses that access locations
1230 // after the pointer are considered as clobbers, which is important to
1231 // catch loop carried dependences.
1232 if (Location.Ptr &&
1233 !IsGuaranteedLoopInvariant(const_cast<Value *>(Location.Ptr)))
1234 CurrentPair.second =
1235 Location.getWithNewSize(LocationSize::beforeOrAfterPointer());
1236 PHITransAddr Translator(
1237 const_cast<Value *>(Location.Ptr),
1238 OriginalAccess->getBlock()->getModule()->getDataLayout(), nullptr);
1239
1240 if (!Translator.PHITranslateValue(OriginalAccess->getBlock(),
1241 DefIterator.getPhiArgBlock(), DT,
1242 true)) {
1243 Value *TransAddr = Translator.getAddr();
1244 if (TransAddr != Location.Ptr) {
1245 CurrentPair.second = CurrentPair.second.getWithNewPtr(TransAddr);
1246
1247 if (TransAddr &&
1248 !IsGuaranteedLoopInvariant(const_cast<Value *>(TransAddr)))
1249 CurrentPair.second = CurrentPair.second.getWithNewSize(
1250 LocationSize::beforeOrAfterPointer());
1251
1252 if (PerformedPhiTranslation)
1253 *PerformedPhiTranslation = true;
1254 }
1255 }
1256 }
1257 }
1258
1259 MemoryAccessPair CurrentPair;
1260 memoryaccess_def_iterator DefIterator;
1261 MemoryLocation Location;
1262 MemoryAccess *OriginalAccess = nullptr;
1263 DominatorTree *DT = nullptr;
1264 bool WalkingPhi = false;
1265 bool *PerformedPhiTranslation = nullptr;
1266};
1267
1268inline upward_defs_iterator
1269upward_defs_begin(const MemoryAccessPair &Pair, DominatorTree &DT,
1270 bool *PerformedPhiTranslation = nullptr) {
1271 return upward_defs_iterator(Pair, &DT, PerformedPhiTranslation);
1272}
1273
1274inline upward_defs_iterator upward_defs_end() { return upward_defs_iterator(); }
1275
1276inline iterator_range<upward_defs_iterator>
1277upward_defs(const MemoryAccessPair &Pair, DominatorTree &DT) {
1278 return make_range(upward_defs_begin(Pair, DT), upward_defs_end());
1279}
1280
1281/// Walks the defining accesses of MemoryDefs. Stops after we hit something that
1282/// has no defining use (e.g. a MemoryPhi or liveOnEntry). Note that, when
1283/// comparing against a null def_chain_iterator, this will compare equal only
1284/// after walking said Phi/liveOnEntry.
1285///
1286/// The UseOptimizedChain flag specifies whether to walk the clobbering
1287/// access chain, or all the accesses.
1288///
1289/// Normally, MemoryDef are all just def/use linked together, so a def_chain on
1290/// a MemoryDef will walk all MemoryDefs above it in the program until it hits
1291/// a phi node. The optimized chain walks the clobbering access of a store.
1292/// So if you are just trying to find, given a store, what the next
1293/// thing that would clobber the same memory is, you want the optimized chain.
1294template <class T, bool UseOptimizedChain = false>
1295struct def_chain_iterator
1296 : public iterator_facade_base<def_chain_iterator<T, UseOptimizedChain>,
1297 std::forward_iterator_tag, MemoryAccess *> {
1298 def_chain_iterator() : MA(nullptr) {}
1299 def_chain_iterator(T MA) : MA(MA) {}
1300
1301 T operator*() const { return MA; }
1302
1303 def_chain_iterator &operator++() {
1304 // N.B. liveOnEntry has a null defining access.
1305 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1306 if (UseOptimizedChain && MUD->isOptimized())
1307 MA = MUD->getOptimized();
1308 else
1309 MA = MUD->getDefiningAccess();
1310 } else {
1311 MA = nullptr;
1312 }
1313
1314 return *this;
1315 }
1316
1317 bool operator==(const def_chain_iterator &O) const { return MA == O.MA; }
1318
1319private:
1320 T MA;
1321};
1322
1323template <class T>
1324inline iterator_range<def_chain_iterator<T>>
1325def_chain(T MA, MemoryAccess *UpTo = nullptr) {
1326#ifdef EXPENSIVE_CHECKS
1327 assert((!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator<T>()) &&(static_cast <bool> ((!UpTo || find(def_chain(MA), UpTo
) != def_chain_iterator<T>()) && "UpTo isn't in the def chain!"
) ? 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~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 1328, __extension__ __PRETTY_FUNCTION__))
1328 "UpTo isn't in the def chain!")(static_cast <bool> ((!UpTo || find(def_chain(MA), UpTo
) != def_chain_iterator<T>()) && "UpTo isn't in the def chain!"
) ? 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~++20210621111111+acefe0eaaf82/llvm/include/llvm/Analysis/MemorySSA.h"
, 1328, __extension__ __PRETTY_FUNCTION__))
;
1329#endif
1330 return make_range(def_chain_iterator<T>(MA), def_chain_iterator<T>(UpTo));
1331}
1332
1333template <class T>
1334inline iterator_range<def_chain_iterator<T, true>> optimized_def_chain(T MA) {
1335 return make_range(def_chain_iterator<T, true>(MA),
1336 def_chain_iterator<T, true>(nullptr));
1337}
1338
1339} // end namespace llvm
1340
1341#endif // LLVM_ANALYSIS_MEMORYSSA_H