blob: 7a3f2db883199d955655dfbc84d133d9d21d26ba [file] [log] [blame]
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001//===- MemorySSA.cpp - Memory SSA Builder ---------------------------------===//
George Burgess IVe1100f52016-02-02 22:46:49 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
George Burgess IVe1100f52016-02-02 22:46:49 +00006//
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00007//===----------------------------------------------------------------------===//
George Burgess IVe1100f52016-02-02 22:46:49 +00008//
9// This file implements the MemorySSA class.
10//
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000011//===----------------------------------------------------------------------===//
12
Daniel Berlin554dcd82017-04-11 20:06:36 +000013#include "llvm/Analysis/MemorySSA.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000014#include "llvm/ADT/DenseMap.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000015#include "llvm/ADT/DenseMapInfo.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000016#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/DepthFirstIterator.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000018#include "llvm/ADT/Hashing.h"
19#include "llvm/ADT/None.h"
20#include "llvm/ADT/Optional.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000021#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000023#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/iterator.h"
25#include "llvm/ADT/iterator_range.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000026#include "llvm/Analysis/AliasAnalysis.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000027#include "llvm/Analysis/IteratedDominanceFrontier.h"
28#include "llvm/Analysis/MemoryLocation.h"
Nico Weber432a3882018-04-30 14:59:11 +000029#include "llvm/Config/llvm-config.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000030#include "llvm/IR/AssemblyAnnotationWriter.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000031#include "llvm/IR/BasicBlock.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000032#include "llvm/IR/Dominators.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000033#include "llvm/IR/Function.h"
34#include "llvm/IR/Instruction.h"
35#include "llvm/IR/Instructions.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000036#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000037#include "llvm/IR/Intrinsics.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000038#include "llvm/IR/LLVMContext.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000039#include "llvm/IR/PassManager.h"
40#include "llvm/IR/Use.h"
41#include "llvm/Pass.h"
42#include "llvm/Support/AtomicOrdering.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/CommandLine.h"
45#include "llvm/Support/Compiler.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000046#include "llvm/Support/Debug.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000047#include "llvm/Support/ErrorHandling.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000048#include "llvm/Support/FormattedStream.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000049#include "llvm/Support/raw_ostream.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000050#include <algorithm>
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000051#include <cassert>
52#include <iterator>
53#include <memory>
54#include <utility>
55
56using namespace llvm;
George Burgess IVe1100f52016-02-02 22:46:49 +000057
58#define DEBUG_TYPE "memoryssa"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000059
Geoff Berryefb0dd12016-06-14 21:19:40 +000060INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
Geoff Berryb96d3b22016-06-01 21:30:40 +000061 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000062INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
63INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Geoff Berryefb0dd12016-06-14 21:19:40 +000064INITIALIZE_PASS_END(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
65 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000066
Chad Rosier232e29e2016-07-06 21:20:47 +000067INITIALIZE_PASS_BEGIN(MemorySSAPrinterLegacyPass, "print-memoryssa",
68 "Memory SSA Printer", false, false)
69INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
70INITIALIZE_PASS_END(MemorySSAPrinterLegacyPass, "print-memoryssa",
71 "Memory SSA Printer", false, false)
72
Daniel Berlinc43aa5a2016-08-02 16:24:03 +000073static cl::opt<unsigned> MaxCheckLimit(
74 "memssa-check-limit", cl::Hidden, cl::init(100),
75 cl::desc("The maximum number of stores/phis MemorySSA"
76 "will consider trying to walk past (default = 100)"));
77
Alina Sbirleacc2e8cc2018-08-15 17:34:55 +000078// Always verify MemorySSA if expensive checking is enabled.
79#ifdef EXPENSIVE_CHECKS
80bool llvm::VerifyMemorySSA = true;
81#else
82bool llvm::VerifyMemorySSA = false;
83#endif
84static cl::opt<bool, true>
85 VerifyMemorySSAX("verify-memoryssa", cl::location(VerifyMemorySSA),
86 cl::Hidden, cl::desc("Enable verification of MemorySSA."));
Chad Rosier232e29e2016-07-06 21:20:47 +000087
George Burgess IVe1100f52016-02-02 22:46:49 +000088namespace llvm {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000089
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000090/// An assembly annotator class to print Memory SSA information in
George Burgess IVe1100f52016-02-02 22:46:49 +000091/// comments.
92class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
93 friend class MemorySSA;
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000094
George Burgess IVe1100f52016-02-02 22:46:49 +000095 const MemorySSA *MSSA;
96
97public:
98 MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
99
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000100 void emitBasicBlockStartAnnot(const BasicBlock *BB,
101 formatted_raw_ostream &OS) override {
George Burgess IVe1100f52016-02-02 22:46:49 +0000102 if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
103 OS << "; " << *MA << "\n";
104 }
105
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000106 void emitInstructionAnnot(const Instruction *I,
107 formatted_raw_ostream &OS) override {
George Burgess IVe1100f52016-02-02 22:46:49 +0000108 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
109 OS << "; " << *MA << "\n";
110 }
111};
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000112
113} // end namespace llvm
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000114
George Burgess IV5f308972016-07-19 01:29:15 +0000115namespace {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000116
Daniel Berlindff31de2016-08-02 21:57:52 +0000117/// Our current alias analysis API differentiates heavily between calls and
118/// non-calls, and functions called on one usually assert on the other.
119/// This class encapsulates the distinction to simplify other code that wants
120/// "Memory affecting instructions and related data" to use as a key.
121/// For example, this class is used as a densemap key in the use optimizer.
122class MemoryLocOrCall {
123public:
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000124 bool IsCall = false;
125
Daniel Berlindff31de2016-08-02 21:57:52 +0000126 MemoryLocOrCall(MemoryUseOrDef *MUD)
127 : MemoryLocOrCall(MUD->getMemoryInst()) {}
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000128 MemoryLocOrCall(const MemoryUseOrDef *MUD)
129 : MemoryLocOrCall(MUD->getMemoryInst()) {}
Daniel Berlindff31de2016-08-02 21:57:52 +0000130
131 MemoryLocOrCall(Instruction *Inst) {
Chandler Carruth363ac682019-01-07 05:42:51 +0000132 if (auto *C = dyn_cast<CallBase>(Inst)) {
Daniel Berlindff31de2016-08-02 21:57:52 +0000133 IsCall = true;
Chandler Carruth363ac682019-01-07 05:42:51 +0000134 Call = C;
Daniel Berlindff31de2016-08-02 21:57:52 +0000135 } else {
136 IsCall = false;
137 // There is no such thing as a memorylocation for a fence inst, and it is
138 // unique in that regard.
139 if (!isa<FenceInst>(Inst))
140 Loc = MemoryLocation::get(Inst);
141 }
142 }
143
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000144 explicit MemoryLocOrCall(const MemoryLocation &Loc) : Loc(Loc) {}
Daniel Berlindff31de2016-08-02 21:57:52 +0000145
Chandler Carruth363ac682019-01-07 05:42:51 +0000146 const CallBase *getCall() const {
Daniel Berlindff31de2016-08-02 21:57:52 +0000147 assert(IsCall);
Chandler Carruth363ac682019-01-07 05:42:51 +0000148 return Call;
Daniel Berlindff31de2016-08-02 21:57:52 +0000149 }
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000150
Daniel Berlindff31de2016-08-02 21:57:52 +0000151 MemoryLocation getLoc() const {
152 assert(!IsCall);
153 return Loc;
154 }
155
156 bool operator==(const MemoryLocOrCall &Other) const {
157 if (IsCall != Other.IsCall)
158 return false;
159
George Burgess IV3588fd42018-03-29 00:54:39 +0000160 if (!IsCall)
161 return Loc == Other.Loc;
162
Chandler Carruth363ac682019-01-07 05:42:51 +0000163 if (Call->getCalledValue() != Other.Call->getCalledValue())
George Burgess IV3588fd42018-03-29 00:54:39 +0000164 return false;
165
Chandler Carruth363ac682019-01-07 05:42:51 +0000166 return Call->arg_size() == Other.Call->arg_size() &&
167 std::equal(Call->arg_begin(), Call->arg_end(),
168 Other.Call->arg_begin());
Daniel Berlindff31de2016-08-02 21:57:52 +0000169 }
170
171private:
Daniel Berlinf5361132016-10-22 04:15:41 +0000172 union {
Chandler Carruth363ac682019-01-07 05:42:51 +0000173 const CallBase *Call;
Daniel Berlind602e042017-01-25 20:56:19 +0000174 MemoryLocation Loc;
Daniel Berlinf5361132016-10-22 04:15:41 +0000175 };
Daniel Berlindff31de2016-08-02 21:57:52 +0000176};
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000177
178} // end anonymous namespace
Daniel Berlindff31de2016-08-02 21:57:52 +0000179
180namespace llvm {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000181
Daniel Berlindff31de2016-08-02 21:57:52 +0000182template <> struct DenseMapInfo<MemoryLocOrCall> {
183 static inline MemoryLocOrCall getEmptyKey() {
184 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getEmptyKey());
185 }
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000186
Daniel Berlindff31de2016-08-02 21:57:52 +0000187 static inline MemoryLocOrCall getTombstoneKey() {
188 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getTombstoneKey());
189 }
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000190
Daniel Berlindff31de2016-08-02 21:57:52 +0000191 static unsigned getHashValue(const MemoryLocOrCall &MLOC) {
George Burgess IV3588fd42018-03-29 00:54:39 +0000192 if (!MLOC.IsCall)
193 return hash_combine(
194 MLOC.IsCall,
195 DenseMapInfo<MemoryLocation>::getHashValue(MLOC.getLoc()));
196
197 hash_code hash =
198 hash_combine(MLOC.IsCall, DenseMapInfo<const Value *>::getHashValue(
Chandler Carruth363ac682019-01-07 05:42:51 +0000199 MLOC.getCall()->getCalledValue()));
George Burgess IV3588fd42018-03-29 00:54:39 +0000200
Chandler Carruth363ac682019-01-07 05:42:51 +0000201 for (const Value *Arg : MLOC.getCall()->args())
George Burgess IV3588fd42018-03-29 00:54:39 +0000202 hash = hash_combine(hash, DenseMapInfo<const Value *>::getHashValue(Arg));
203 return hash;
Daniel Berlindff31de2016-08-02 21:57:52 +0000204 }
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000205
Daniel Berlindff31de2016-08-02 21:57:52 +0000206 static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS) {
207 return LHS == RHS;
208 }
209};
Daniel Berlindf101192016-08-03 00:01:46 +0000210
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000211} // end namespace llvm
212
George Burgess IV82e355c2016-08-03 19:39:54 +0000213/// This does one-way checks to see if Use could theoretically be hoisted above
214/// MayClobber. This will not check the other way around.
215///
216/// This assumes that, for the purposes of MemorySSA, Use comes directly after
217/// MayClobber, with no potentially clobbering operations in between them.
218/// (Where potentially clobbering ops are memory barriers, aliased stores, etc.)
Alina Sbirleaca741a82017-12-22 19:54:03 +0000219static bool areLoadsReorderable(const LoadInst *Use,
220 const LoadInst *MayClobber) {
George Burgess IV82e355c2016-08-03 19:39:54 +0000221 bool VolatileUse = Use->isVolatile();
222 bool VolatileClobber = MayClobber->isVolatile();
223 // Volatile operations may never be reordered with other volatile operations.
224 if (VolatileUse && VolatileClobber)
Alina Sbirleaca741a82017-12-22 19:54:03 +0000225 return false;
226 // Otherwise, volatile doesn't matter here. From the language reference:
227 // 'optimizers may change the order of volatile operations relative to
228 // non-volatile operations.'"
George Burgess IV82e355c2016-08-03 19:39:54 +0000229
230 // If a load is seq_cst, it cannot be moved above other loads. If its ordering
231 // is weaker, it can be moved above other loads. We just need to be sure that
232 // MayClobber isn't an acquire load, because loads can't be moved above
233 // acquire loads.
234 //
235 // Note that this explicitly *does* allow the free reordering of monotonic (or
236 // weaker) loads of the same address.
237 bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent;
238 bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(),
239 AtomicOrdering::Acquire);
Alina Sbirleaca741a82017-12-22 19:54:03 +0000240 return !(SeqCstUse || MayClobberIsAcquire);
George Burgess IV82e355c2016-08-03 19:39:54 +0000241}
242
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000243namespace {
244
245struct ClobberAlias {
246 bool IsClobber;
247 Optional<AliasResult> AR;
248};
249
250} // end anonymous namespace
251
252// Return a pair of {IsClobber (bool), AR (AliasResult)}. It relies on AR being
253// ignored if IsClobber = false.
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000254template <typename AliasAnalysisType>
255static ClobberAlias
256instructionClobbersQuery(const MemoryDef *MD, const MemoryLocation &UseLoc,
257 const Instruction *UseInst, AliasAnalysisType &AA) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000258 Instruction *DefInst = MD->getMemoryInst();
259 assert(DefInst && "Defining instruction not actually an instruction");
Chandler Carruth363ac682019-01-07 05:42:51 +0000260 const auto *UseCall = dyn_cast<CallBase>(UseInst);
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000261 Optional<AliasResult> AR;
George Burgess IV5f308972016-07-19 01:29:15 +0000262
Daniel Berlindf101192016-08-03 00:01:46 +0000263 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
264 // These intrinsics will show up as affecting memory, but they are just
George Burgess IVff08c802018-08-10 05:14:43 +0000265 // markers, mostly.
266 //
267 // FIXME: We probably don't actually want MemorySSA to model these at all
268 // (including creating MemoryAccesses for them): we just end up inventing
269 // clobbers where they don't really exist at all. Please see D43269 for
270 // context.
Daniel Berlindf101192016-08-03 00:01:46 +0000271 switch (II->getIntrinsicID()) {
272 case Intrinsic::lifetime_start:
Chandler Carruth363ac682019-01-07 05:42:51 +0000273 if (UseCall)
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000274 return {false, NoAlias};
275 AR = AA.alias(MemoryLocation(II->getArgOperand(1)), UseLoc);
George Burgess IVff08c802018-08-10 05:14:43 +0000276 return {AR != NoAlias, AR};
Daniel Berlindf101192016-08-03 00:01:46 +0000277 case Intrinsic::lifetime_end:
278 case Intrinsic::invariant_start:
279 case Intrinsic::invariant_end:
280 case Intrinsic::assume:
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000281 return {false, NoAlias};
Daniel Berlindf101192016-08-03 00:01:46 +0000282 default:
283 break;
284 }
285 }
286
Chandler Carruth363ac682019-01-07 05:42:51 +0000287 if (UseCall) {
288 ModRefInfo I = AA.getModRefInfo(DefInst, UseCall);
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000289 AR = isMustSet(I) ? MustAlias : MayAlias;
290 return {isModOrRefSet(I), AR};
Hans Wennborg70e22d12017-11-21 18:00:01 +0000291 }
George Burgess IV82e355c2016-08-03 19:39:54 +0000292
Alina Sbirleaca741a82017-12-22 19:54:03 +0000293 if (auto *DefLoad = dyn_cast<LoadInst>(DefInst))
294 if (auto *UseLoad = dyn_cast<LoadInst>(UseInst))
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000295 return {!areLoadsReorderable(UseLoad, DefLoad), MayAlias};
George Burgess IV82e355c2016-08-03 19:39:54 +0000296
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000297 ModRefInfo I = AA.getModRefInfo(DefInst, UseLoc);
298 AR = isMustSet(I) ? MustAlias : MayAlias;
299 return {isModSet(I), AR};
Daniel Berlindff31de2016-08-02 21:57:52 +0000300}
301
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000302template <typename AliasAnalysisType>
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000303static ClobberAlias instructionClobbersQuery(MemoryDef *MD,
304 const MemoryUseOrDef *MU,
305 const MemoryLocOrCall &UseMLOC,
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000306 AliasAnalysisType &AA) {
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000307 // FIXME: This is a temporary hack to allow a single instructionClobbersQuery
308 // to exist while MemoryLocOrCall is pushed through places.
309 if (UseMLOC.IsCall)
310 return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(),
311 AA);
312 return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(),
313 AA);
314}
315
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000316// Return true when MD may alias MU, return false otherwise.
Daniel Berlindcb004f2017-03-02 23:06:46 +0000317bool MemorySSAUtil::defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
318 AliasAnalysis &AA) {
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000319 return instructionClobbersQuery(MD, MU, MemoryLocOrCall(MU), AA).IsClobber;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000320}
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000321
322namespace {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000323
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000324struct UpwardsMemoryQuery {
325 // True if our original query started off as a call
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000326 bool IsCall = false;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000327 // The pointer location we started the query with. This will be empty if
328 // IsCall is true.
329 MemoryLocation StartingLoc;
330 // This is the instruction we were querying about.
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000331 const Instruction *Inst = nullptr;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000332 // The MemoryAccess we actually got called with, used to test local domination
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000333 const MemoryAccess *OriginalAccess = nullptr;
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000334 Optional<AliasResult> AR = MayAlias;
Alina Sbirleaf7230202019-01-07 18:40:27 +0000335 bool SkipSelfAccess = false;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000336
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000337 UpwardsMemoryQuery() = default;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000338
339 UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
Chandler Carruth363ac682019-01-07 05:42:51 +0000340 : IsCall(isa<CallBase>(Inst)), Inst(Inst), OriginalAccess(Access) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000341 if (!IsCall)
342 StartingLoc = MemoryLocation::get(Inst);
343 }
344};
345
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000346} // end anonymous namespace
347
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000348static bool lifetimeEndsAt(MemoryDef *MD, const MemoryLocation &Loc,
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000349 BatchAAResults &AA) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000350 Instruction *Inst = MD->getMemoryInst();
351 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
352 switch (II->getIntrinsicID()) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000353 case Intrinsic::lifetime_end:
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000354 return AA.alias(MemoryLocation(II->getArgOperand(1)), Loc) == MustAlias;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000355 default:
356 return false;
357 }
358 }
359 return false;
360}
361
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000362template <typename AliasAnalysisType>
363static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysisType &AA,
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000364 const Instruction *I) {
365 // If the memory can't be changed, then loads of the memory can't be
366 // clobbered.
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000367 return isa<LoadInst>(I) && (I->getMetadata(LLVMContext::MD_invariant_load) ||
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000368 AA.pointsToConstantMemory(MemoryLocation(
369 cast<LoadInst>(I)->getPointerOperand())));
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000370}
371
George Burgess IV5f308972016-07-19 01:29:15 +0000372/// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
373/// inbetween `Start` and `ClobberAt` can clobbers `Start`.
374///
375/// This is meant to be as simple and self-contained as possible. Because it
376/// uses no cache, etc., it can be relatively expensive.
377///
378/// \param Start The MemoryAccess that we want to walk from.
379/// \param ClobberAt A clobber for Start.
380/// \param StartLoc The MemoryLocation for Start.
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000381/// \param MSSA The MemorySSA instance that Start and ClobberAt belong to.
George Burgess IV5f308972016-07-19 01:29:15 +0000382/// \param Query The UpwardsMemoryQuery we used for our search.
383/// \param AA The AliasAnalysis we used for our search.
Alina Sbirlea65f385d2018-09-07 23:51:41 +0000384/// \param AllowImpreciseClobber Always false, unless we do relaxed verify.
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000385
386template <typename AliasAnalysisType>
Alina Sbirlead77edc02019-02-11 19:51:21 +0000387LLVM_ATTRIBUTE_UNUSED static void
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000388checkClobberSanity(const MemoryAccess *Start, MemoryAccess *ClobberAt,
George Burgess IV5f308972016-07-19 01:29:15 +0000389 const MemoryLocation &StartLoc, const MemorySSA &MSSA,
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000390 const UpwardsMemoryQuery &Query, AliasAnalysisType &AA,
Alina Sbirlea65f385d2018-09-07 23:51:41 +0000391 bool AllowImpreciseClobber = false) {
George Burgess IV5f308972016-07-19 01:29:15 +0000392 assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
393
394 if (MSSA.isLiveOnEntryDef(Start)) {
395 assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
396 "liveOnEntry must clobber itself");
397 return;
398 }
399
George Burgess IV5f308972016-07-19 01:29:15 +0000400 bool FoundClobber = false;
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000401 DenseSet<ConstMemoryAccessPair> VisitedPhis;
402 SmallVector<ConstMemoryAccessPair, 8> Worklist;
George Burgess IV5f308972016-07-19 01:29:15 +0000403 Worklist.emplace_back(Start, StartLoc);
404 // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
405 // is found, complain.
406 while (!Worklist.empty()) {
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000407 auto MAP = Worklist.pop_back_val();
George Burgess IV5f308972016-07-19 01:29:15 +0000408 // All we care about is that nothing from Start to ClobberAt clobbers Start.
409 // We learn nothing from revisiting nodes.
410 if (!VisitedPhis.insert(MAP).second)
411 continue;
412
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000413 for (const auto *MA : def_chain(MAP.first)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000414 if (MA == ClobberAt) {
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000415 if (const auto *MD = dyn_cast<MemoryDef>(MA)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000416 // instructionClobbersQuery isn't essentially free, so don't use `|=`,
417 // since it won't let us short-circuit.
418 //
419 // Also, note that this can't be hoisted out of the `Worklist` loop,
420 // since MD may only act as a clobber for 1 of N MemoryLocations.
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000421 FoundClobber = FoundClobber || MSSA.isLiveOnEntryDef(MD);
422 if (!FoundClobber) {
423 ClobberAlias CA =
424 instructionClobbersQuery(MD, MAP.second, Query.Inst, AA);
425 if (CA.IsClobber) {
426 FoundClobber = true;
427 // Not used: CA.AR;
428 }
429 }
George Burgess IV5f308972016-07-19 01:29:15 +0000430 }
431 break;
432 }
433
434 // We should never hit liveOnEntry, unless it's the clobber.
435 assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
436
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000437 if (const auto *MD = dyn_cast<MemoryDef>(MA)) {
Alina Sbirlea5bce4d52018-08-29 22:38:51 +0000438 // If Start is a Def, skip self.
439 if (MD == Start)
440 continue;
441
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000442 assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA)
443 .IsClobber &&
George Burgess IV5f308972016-07-19 01:29:15 +0000444 "Found clobber before reaching ClobberAt!");
445 continue;
446 }
447
Alina Sbirlea5bce4d52018-08-29 22:38:51 +0000448 if (const auto *MU = dyn_cast<MemoryUse>(MA)) {
Alina Sbirlea6edcc9e2018-08-29 23:20:29 +0000449 (void)MU;
Alina Sbirlea5bce4d52018-08-29 22:38:51 +0000450 assert (MU == Start &&
451 "Can only find use in def chain if Start is a use");
452 continue;
453 }
454
George Burgess IV5f308972016-07-19 01:29:15 +0000455 assert(isa<MemoryPhi>(MA));
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000456 Worklist.append(
457 upward_defs_begin({const_cast<MemoryAccess *>(MA), MAP.second}),
458 upward_defs_end());
George Burgess IV5f308972016-07-19 01:29:15 +0000459 }
460 }
461
Alina Sbirlea65f385d2018-09-07 23:51:41 +0000462 // If the verify is done following an optimization, it's possible that
463 // ClobberAt was a conservative clobbering, that we can now infer is not a
464 // true clobbering access. Don't fail the verify if that's the case.
465 // We do have accesses that claim they're optimized, but could be optimized
466 // further. Updating all these can be expensive, so allow it for now (FIXME).
467 if (AllowImpreciseClobber)
468 return;
469
George Burgess IV5f308972016-07-19 01:29:15 +0000470 // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
471 // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
472 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
473 "ClobberAt never acted as a clobber");
474}
475
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000476namespace {
477
George Burgess IV5f308972016-07-19 01:29:15 +0000478/// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
479/// in one class.
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000480template <class AliasAnalysisType> class ClobberWalker {
George Burgess IV5f308972016-07-19 01:29:15 +0000481 /// Save a few bytes by using unsigned instead of size_t.
482 using ListIndex = unsigned;
483
484 /// Represents a span of contiguous MemoryDefs, potentially ending in a
485 /// MemoryPhi.
486 struct DefPath {
487 MemoryLocation Loc;
488 // Note that, because we always walk in reverse, Last will always dominate
489 // First. Also note that First and Last are inclusive.
490 MemoryAccess *First;
491 MemoryAccess *Last;
George Burgess IV5f308972016-07-19 01:29:15 +0000492 Optional<ListIndex> Previous;
493
494 DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
495 Optional<ListIndex> Previous)
496 : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
497
498 DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
499 Optional<ListIndex> Previous)
500 : DefPath(Loc, Init, Init, Previous) {}
501 };
502
503 const MemorySSA &MSSA;
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000504 AliasAnalysisType &AA;
George Burgess IV5f308972016-07-19 01:29:15 +0000505 DominatorTree &DT;
George Burgess IV5f308972016-07-19 01:29:15 +0000506 UpwardsMemoryQuery *Query;
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000507 unsigned *UpwardWalkLimit;
George Burgess IV5f308972016-07-19 01:29:15 +0000508
509 // Phi optimization bookkeeping
510 SmallVector<DefPath, 32> Paths;
511 DenseSet<ConstMemoryAccessPair> VisitedPhis;
George Burgess IV5f308972016-07-19 01:29:15 +0000512
George Burgess IV5f308972016-07-19 01:29:15 +0000513 /// Find the nearest def or phi that `From` can legally be optimized to.
Daniel Berlind0420312017-04-01 09:01:12 +0000514 const MemoryAccess *getWalkTarget(const MemoryPhi *From) const {
George Burgess IV5f308972016-07-19 01:29:15 +0000515 assert(From->getNumOperands() && "Phi with no operands?");
516
517 BasicBlock *BB = From->getBlock();
George Burgess IV5f308972016-07-19 01:29:15 +0000518 MemoryAccess *Result = MSSA.getLiveOnEntryDef();
519 DomTreeNode *Node = DT.getNode(BB);
520 while ((Node = Node->getIDom())) {
Daniel Berlin7500c562017-04-01 08:59:45 +0000521 auto *Defs = MSSA.getBlockDefs(Node->getBlock());
522 if (Defs)
Daniel Berlind0420312017-04-01 09:01:12 +0000523 return &*Defs->rbegin();
George Burgess IV5f308972016-07-19 01:29:15 +0000524 }
George Burgess IV5f308972016-07-19 01:29:15 +0000525 return Result;
526 }
527
528 /// Result of calling walkToPhiOrClobber.
529 struct UpwardsWalkResult {
530 /// The "Result" of the walk. Either a clobber, the last thing we walked, or
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000531 /// both. Include alias info when clobber found.
George Burgess IV5f308972016-07-19 01:29:15 +0000532 MemoryAccess *Result;
533 bool IsKnownClobber;
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000534 Optional<AliasResult> AR;
George Burgess IV5f308972016-07-19 01:29:15 +0000535 };
536
537 /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
538 /// This will update Desc.Last as it walks. It will (optionally) also stop at
539 /// StopAt.
540 ///
541 /// This does not test for whether StopAt is a clobber
Daniel Berlind0420312017-04-01 09:01:12 +0000542 UpwardsWalkResult
Alina Sbirleaf7230202019-01-07 18:40:27 +0000543 walkToPhiOrClobber(DefPath &Desc, const MemoryAccess *StopAt = nullptr,
544 const MemoryAccess *SkipStopAt = nullptr) const {
George Burgess IV5f308972016-07-19 01:29:15 +0000545 assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000546 assert(UpwardWalkLimit && *UpwardWalkLimit > 0 &&
547 "Need a positive walk limit");
George Burgess IV5f308972016-07-19 01:29:15 +0000548
549 for (MemoryAccess *Current : def_chain(Desc.Last)) {
550 Desc.Last = Current;
Alina Sbirleaf7230202019-01-07 18:40:27 +0000551 if (Current == StopAt || Current == SkipStopAt)
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000552 return {Current, false, MayAlias};
George Burgess IV5f308972016-07-19 01:29:15 +0000553
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000554 if (auto *MD = dyn_cast<MemoryDef>(Current)) {
555 if (MSSA.isLiveOnEntryDef(MD))
556 return {MD, true, MustAlias};
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000557
558 if (!--*UpwardWalkLimit)
559 return {Current, true, MayAlias};
560
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000561 ClobberAlias CA =
562 instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA);
563 if (CA.IsClobber)
564 return {MD, true, CA.AR};
565 }
George Burgess IV5f308972016-07-19 01:29:15 +0000566 }
567
568 assert(isa<MemoryPhi>(Desc.Last) &&
569 "Ended at a non-clobber that's not a phi?");
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000570 return {Desc.Last, false, MayAlias};
George Burgess IV5f308972016-07-19 01:29:15 +0000571 }
572
573 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
574 ListIndex PriorNode) {
575 auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),
576 upward_defs_end());
577 for (const MemoryAccessPair &P : UpwardDefs) {
578 PausedSearches.push_back(Paths.size());
579 Paths.emplace_back(P.second, P.first, PriorNode);
580 }
581 }
582
583 /// Represents a search that terminated after finding a clobber. This clobber
584 /// may or may not be present in the path of defs from LastNode..SearchStart,
585 /// since it may have been retrieved from cache.
586 struct TerminatedPath {
587 MemoryAccess *Clobber;
588 ListIndex LastNode;
589 };
590
591 /// Get an access that keeps us from optimizing to the given phi.
592 ///
593 /// PausedSearches is an array of indices into the Paths array. Its incoming
594 /// value is the indices of searches that stopped at the last phi optimization
595 /// target. It's left in an unspecified state.
596 ///
597 /// If this returns None, NewPaused is a vector of searches that terminated
598 /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
George Burgess IV14633b52016-08-03 01:22:19 +0000599 Optional<TerminatedPath>
Daniel Berlind0420312017-04-01 09:01:12 +0000600 getBlockingAccess(const MemoryAccess *StopWhere,
George Burgess IV5f308972016-07-19 01:29:15 +0000601 SmallVectorImpl<ListIndex> &PausedSearches,
602 SmallVectorImpl<ListIndex> &NewPaused,
603 SmallVectorImpl<TerminatedPath> &Terminated) {
604 assert(!PausedSearches.empty() && "No searches to continue?");
605
606 // BFS vs DFS really doesn't make a difference here, so just do a DFS with
607 // PausedSearches as our stack.
608 while (!PausedSearches.empty()) {
609 ListIndex PathIndex = PausedSearches.pop_back_val();
610 DefPath &Node = Paths[PathIndex];
611
612 // If we've already visited this path with this MemoryLocation, we don't
613 // need to do so again.
614 //
615 // NOTE: That we just drop these paths on the ground makes caching
616 // behavior sporadic. e.g. given a diamond:
617 // A
618 // B C
619 // D
620 //
621 // ...If we walk D, B, A, C, we'll only cache the result of phi
622 // optimization for A, B, and D; C will be skipped because it dies here.
623 // This arguably isn't the worst thing ever, since:
624 // - We generally query things in a top-down order, so if we got below D
625 // without needing cache entries for {C, MemLoc}, then chances are
626 // that those cache entries would end up ultimately unused.
627 // - We still cache things for A, so C only needs to walk up a bit.
628 // If this behavior becomes problematic, we can fix without a ton of extra
629 // work.
630 if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
631 continue;
632
Alina Sbirleaf7230202019-01-07 18:40:27 +0000633 const MemoryAccess *SkipStopWhere = nullptr;
634 if (Query->SkipSelfAccess && Node.Loc == Query->StartingLoc) {
635 assert(isa<MemoryDef>(Query->OriginalAccess));
636 SkipStopWhere = Query->OriginalAccess;
637 }
638
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000639 UpwardsWalkResult Res = walkToPhiOrClobber(Node,
640 /*StopAt=*/StopWhere,
Alina Sbirleaf7230202019-01-07 18:40:27 +0000641 /*SkipStopAt=*/SkipStopWhere);
George Burgess IV5f308972016-07-19 01:29:15 +0000642 if (Res.IsKnownClobber) {
Alina Sbirleaf7230202019-01-07 18:40:27 +0000643 assert(Res.Result != StopWhere && Res.Result != SkipStopWhere);
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000644
George Burgess IV5f308972016-07-19 01:29:15 +0000645 // If this wasn't a cache hit, we hit a clobber when walking. That's a
646 // failure.
George Burgess IV14633b52016-08-03 01:22:19 +0000647 TerminatedPath Term{Res.Result, PathIndex};
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000648 if (!MSSA.dominates(Res.Result, StopWhere))
George Burgess IV14633b52016-08-03 01:22:19 +0000649 return Term;
George Burgess IV5f308972016-07-19 01:29:15 +0000650
651 // Otherwise, it's a valid thing to potentially optimize to.
George Burgess IV14633b52016-08-03 01:22:19 +0000652 Terminated.push_back(Term);
George Burgess IV5f308972016-07-19 01:29:15 +0000653 continue;
654 }
655
Alina Sbirleaf7230202019-01-07 18:40:27 +0000656 if (Res.Result == StopWhere || Res.Result == SkipStopWhere) {
George Burgess IV5f308972016-07-19 01:29:15 +0000657 // We've hit our target. Save this path off for if we want to continue
Alina Sbirleaf7230202019-01-07 18:40:27 +0000658 // walking. If we are in the mode of skipping the OriginalAccess, and
659 // we've reached back to the OriginalAccess, do not save path, we've
660 // just looped back to self.
661 if (Res.Result != SkipStopWhere)
662 NewPaused.push_back(PathIndex);
George Burgess IV5f308972016-07-19 01:29:15 +0000663 continue;
664 }
665
666 assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
667 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
668 }
669
670 return None;
671 }
672
673 template <typename T, typename Walker>
674 struct generic_def_path_iterator
675 : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
676 std::forward_iterator_tag, T *> {
Hans Wennborg5519cb22019-03-25 09:27:42 +0000677 generic_def_path_iterator() {}
George Burgess IV5f308972016-07-19 01:29:15 +0000678 generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
679
680 T &operator*() const { return curNode(); }
681
682 generic_def_path_iterator &operator++() {
683 N = curNode().Previous;
684 return *this;
685 }
686
687 bool operator==(const generic_def_path_iterator &O) const {
688 if (N.hasValue() != O.N.hasValue())
689 return false;
690 return !N.hasValue() || *N == *O.N;
691 }
692
693 private:
694 T &curNode() const { return W->Paths[*N]; }
695
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000696 Walker *W = nullptr;
697 Optional<ListIndex> N = None;
George Burgess IV5f308972016-07-19 01:29:15 +0000698 };
699
700 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
701 using const_def_path_iterator =
702 generic_def_path_iterator<const DefPath, const ClobberWalker>;
703
704 iterator_range<def_path_iterator> def_path(ListIndex From) {
705 return make_range(def_path_iterator(this, From), def_path_iterator());
706 }
707
708 iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
709 return make_range(const_def_path_iterator(this, From),
710 const_def_path_iterator());
711 }
712
713 struct OptznResult {
714 /// The path that contains our result.
715 TerminatedPath PrimaryClobber;
716 /// The paths that we can legally cache back from, but that aren't
717 /// necessarily the result of the Phi optimization.
718 SmallVector<TerminatedPath, 4> OtherClobbers;
719 };
720
721 ListIndex defPathIndex(const DefPath &N) const {
722 // The assert looks nicer if we don't need to do &N
723 const DefPath *NP = &N;
724 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
725 "Out of bounds DefPath!");
726 return NP - &Paths.front();
727 }
728
729 /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
730 /// that act as legal clobbers. Note that this won't return *all* clobbers.
731 ///
732 /// Phi optimization algorithm tl;dr:
733 /// - Find the earliest def/phi, A, we can optimize to
734 /// - Find if all paths from the starting memory access ultimately reach A
735 /// - If not, optimization isn't possible.
736 /// - Otherwise, walk from A to another clobber or phi, A'.
737 /// - If A' is a def, we're done.
738 /// - If A' is a phi, try to optimize it.
739 ///
740 /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
741 /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
742 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
743 const MemoryLocation &Loc) {
744 assert(Paths.empty() && VisitedPhis.empty() &&
745 "Reset the optimization state.");
746
747 Paths.emplace_back(Loc, Start, Phi, None);
748 // Stores how many "valid" optimization nodes we had prior to calling
749 // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
750 auto PriorPathsSize = Paths.size();
751
752 SmallVector<ListIndex, 16> PausedSearches;
753 SmallVector<ListIndex, 8> NewPaused;
754 SmallVector<TerminatedPath, 4> TerminatedPaths;
755
756 addSearches(Phi, PausedSearches, 0);
757
758 // Moves the TerminatedPath with the "most dominated" Clobber to the end of
759 // Paths.
760 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
761 assert(!Paths.empty() && "Need a path to move");
George Burgess IV5f308972016-07-19 01:29:15 +0000762 auto Dom = Paths.begin();
763 for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
764 if (!MSSA.dominates(I->Clobber, Dom->Clobber))
765 Dom = I;
766 auto Last = Paths.end() - 1;
767 if (Last != Dom)
768 std::iter_swap(Last, Dom);
769 };
770
771 MemoryPhi *Current = Phi;
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000772 while (true) {
George Burgess IV5f308972016-07-19 01:29:15 +0000773 assert(!MSSA.isLiveOnEntryDef(Current) &&
774 "liveOnEntry wasn't treated as a clobber?");
775
Daniel Berlind0420312017-04-01 09:01:12 +0000776 const auto *Target = getWalkTarget(Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000777 // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
778 // optimization for the prior phi.
779 assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
780 return MSSA.dominates(P.Clobber, Target);
781 }));
782
783 // FIXME: This is broken, because the Blocker may be reported to be
784 // liveOnEntry, and we'll happily wait for that to disappear (read: never)
George Burgess IV7f414b92016-08-22 23:40:01 +0000785 // For the moment, this is fine, since we do nothing with blocker info.
George Burgess IV14633b52016-08-03 01:22:19 +0000786 if (Optional<TerminatedPath> Blocker = getBlockingAccess(
George Burgess IV5f308972016-07-19 01:29:15 +0000787 Target, PausedSearches, NewPaused, TerminatedPaths)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000788
789 // Find the node we started at. We can't search based on N->Last, since
790 // we may have gone around a loop with a different MemoryLocation.
George Burgess IV14633b52016-08-03 01:22:19 +0000791 auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
George Burgess IV5f308972016-07-19 01:29:15 +0000792 return defPathIndex(N) < PriorPathsSize;
793 });
794 assert(Iter != def_path_iterator());
795
796 DefPath &CurNode = *Iter;
797 assert(CurNode.Last == Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000798
799 // Two things:
800 // A. We can't reliably cache all of NewPaused back. Consider a case
801 // where we have two paths in NewPaused; one of which can't optimize
802 // above this phi, whereas the other can. If we cache the second path
803 // back, we'll end up with suboptimal cache entries. We can handle
804 // cases like this a bit better when we either try to find all
805 // clobbers that block phi optimization, or when our cache starts
806 // supporting unfinished searches.
807 // B. We can't reliably cache TerminatedPaths back here without doing
808 // extra checks; consider a case like:
809 // T
810 // / \
811 // D C
812 // \ /
813 // S
814 // Where T is our target, C is a node with a clobber on it, D is a
815 // diamond (with a clobber *only* on the left or right node, N), and
816 // S is our start. Say we walk to D, through the node opposite N
817 // (read: ignoring the clobber), and see a cache entry in the top
818 // node of D. That cache entry gets put into TerminatedPaths. We then
819 // walk up to C (N is later in our worklist), find the clobber, and
820 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
821 // the bottom part of D to the cached clobber, ignoring the clobber
822 // in N. Again, this problem goes away if we start tracking all
823 // blockers for a given phi optimization.
824 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
825 return {Result, {}};
826 }
827
828 // If there's nothing left to search, then all paths led to valid clobbers
829 // that we got from our cache; pick the nearest to the start, and allow
830 // the rest to be cached back.
831 if (NewPaused.empty()) {
832 MoveDominatedPathToEnd(TerminatedPaths);
833 TerminatedPath Result = TerminatedPaths.pop_back_val();
834 return {Result, std::move(TerminatedPaths)};
835 }
836
837 MemoryAccess *DefChainEnd = nullptr;
838 SmallVector<TerminatedPath, 4> Clobbers;
839 for (ListIndex Paused : NewPaused) {
840 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
841 if (WR.IsKnownClobber)
842 Clobbers.push_back({WR.Result, Paused});
843 else
844 // Micro-opt: If we hit the end of the chain, save it.
845 DefChainEnd = WR.Result;
846 }
847
848 if (!TerminatedPaths.empty()) {
849 // If we couldn't find the dominating phi/liveOnEntry in the above loop,
850 // do it now.
851 if (!DefChainEnd)
Daniel Berlind0420312017-04-01 09:01:12 +0000852 for (auto *MA : def_chain(const_cast<MemoryAccess *>(Target)))
George Burgess IV5f308972016-07-19 01:29:15 +0000853 DefChainEnd = MA;
854
855 // If any of the terminated paths don't dominate the phi we'll try to
856 // optimize, we need to figure out what they are and quit.
857 const BasicBlock *ChainBB = DefChainEnd->getBlock();
858 for (const TerminatedPath &TP : TerminatedPaths) {
859 // Because we know that DefChainEnd is as "high" as we can go, we
860 // don't need local dominance checks; BB dominance is sufficient.
861 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
862 Clobbers.push_back(TP);
863 }
864 }
865
866 // If we have clobbers in the def chain, find the one closest to Current
867 // and quit.
868 if (!Clobbers.empty()) {
869 MoveDominatedPathToEnd(Clobbers);
870 TerminatedPath Result = Clobbers.pop_back_val();
871 return {Result, std::move(Clobbers)};
872 }
873
874 assert(all_of(NewPaused,
875 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
876
877 // Because liveOnEntry is a clobber, this must be a phi.
878 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
879
880 PriorPathsSize = Paths.size();
881 PausedSearches.clear();
882 for (ListIndex I : NewPaused)
883 addSearches(DefChainPhi, PausedSearches, I);
884 NewPaused.clear();
885
886 Current = DefChainPhi;
887 }
888 }
889
George Burgess IV5f308972016-07-19 01:29:15 +0000890 void verifyOptResult(const OptznResult &R) const {
891 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
892 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
893 }));
894 }
895
896 void resetPhiOptznState() {
897 Paths.clear();
898 VisitedPhis.clear();
899 }
900
901public:
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000902 ClobberWalker(const MemorySSA &MSSA, AliasAnalysisType &AA, DominatorTree &DT)
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000903 : MSSA(MSSA), AA(AA), DT(DT) {}
George Burgess IV5f308972016-07-19 01:29:15 +0000904
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000905 AliasAnalysisType *getAA() { return &AA; }
George Burgess IV5f308972016-07-19 01:29:15 +0000906 /// Finds the nearest clobber for the given query, optimizing phis if
907 /// possible.
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000908 MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q,
909 unsigned &UpWalkLimit) {
George Burgess IV5f308972016-07-19 01:29:15 +0000910 Query = &Q;
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000911 UpwardWalkLimit = &UpWalkLimit;
912 // Starting limit must be > 0.
913 if (!UpWalkLimit)
914 UpWalkLimit++;
George Burgess IV5f308972016-07-19 01:29:15 +0000915
916 MemoryAccess *Current = Start;
917 // This walker pretends uses don't exist. If we're handed one, silently grab
918 // its def. (This has the nice side-effect of ensuring we never cache uses)
919 if (auto *MU = dyn_cast<MemoryUse>(Start))
920 Current = MU->getDefiningAccess();
921
922 DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
923 // Fast path for the overly-common case (no crazy phi optimization
924 // necessary)
925 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000926 MemoryAccess *Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000927 if (WalkResult.IsKnownClobber) {
George Burgess IV93ea19b2016-07-24 07:03:49 +0000928 Result = WalkResult.Result;
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000929 Q.AR = WalkResult.AR;
George Burgess IV93ea19b2016-07-24 07:03:49 +0000930 } else {
931 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
932 Current, Q.StartingLoc);
933 verifyOptResult(OptRes);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000934 resetPhiOptznState();
935 Result = OptRes.PrimaryClobber.Clobber;
George Burgess IV5f308972016-07-19 01:29:15 +0000936 }
937
George Burgess IV5f308972016-07-19 01:29:15 +0000938#ifdef EXPENSIVE_CHECKS
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000939 if (!Q.SkipSelfAccess && *UpwardWalkLimit > 0)
Alina Sbirleae41f4b32019-01-10 21:47:15 +0000940 checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000941#endif
George Burgess IV93ea19b2016-07-24 07:03:49 +0000942 return Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000943 }
944};
945
946struct RenamePassData {
947 DomTreeNode *DTN;
948 DomTreeNode::const_iterator ChildIt;
949 MemoryAccess *IncomingVal;
950
951 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
952 MemoryAccess *M)
953 : DTN(D), ChildIt(It), IncomingVal(M) {}
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000954
George Burgess IV5f308972016-07-19 01:29:15 +0000955 void swap(RenamePassData &RHS) {
956 std::swap(DTN, RHS.DTN);
957 std::swap(ChildIt, RHS.ChildIt);
958 std::swap(IncomingVal, RHS.IncomingVal);
959 }
960};
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000961
962} // end anonymous namespace
George Burgess IV5f308972016-07-19 01:29:15 +0000963
964namespace llvm {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000965
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000966template <class AliasAnalysisType> class MemorySSA::ClobberWalkerBase {
967 ClobberWalker<AliasAnalysisType> Walker;
Alina Sbirleabc8aa242019-01-07 19:22:37 +0000968 MemorySSA *MSSA;
969
970public:
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000971 ClobberWalkerBase(MemorySSA *M, AliasAnalysisType *A, DominatorTree *D)
Alina Sbirleabc8aa242019-01-07 19:22:37 +0000972 : Walker(*M, *A, *D), MSSA(M) {}
973
974 MemoryAccess *getClobberingMemoryAccessBase(MemoryAccess *,
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000975 const MemoryLocation &,
976 unsigned &);
977 // Third argument (bool), defines whether the clobber search should skip the
Alina Sbirleabc8aa242019-01-07 19:22:37 +0000978 // original queried access. If true, there will be a follow-up query searching
979 // for a clobber access past "self". Note that the Optimized access is not
980 // updated if a new clobber is found by this SkipSelf search. If this
981 // additional query becomes heavily used we may decide to cache the result.
982 // Walker instantiations will decide how to set the SkipSelf bool.
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000983 MemoryAccess *getClobberingMemoryAccessBase(MemoryAccess *, unsigned &, bool);
Alina Sbirleabc8aa242019-01-07 19:22:37 +0000984};
985
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000986/// A MemorySSAWalker that does AA walks to disambiguate accesses. It no
George Burgess IV45f263d2018-05-26 02:28:55 +0000987/// longer does caching on its own, but the name has been retained for the
988/// moment.
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000989template <class AliasAnalysisType>
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000990class MemorySSA::CachingWalker final : public MemorySSAWalker {
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000991 ClobberWalkerBase<AliasAnalysisType> *Walker;
George Burgess IV5f308972016-07-19 01:29:15 +0000992
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000993public:
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000994 CachingWalker(MemorySSA *M, ClobberWalkerBase<AliasAnalysisType> *W)
Alina Sbirleabc8aa242019-01-07 19:22:37 +0000995 : MemorySSAWalker(M), Walker(W) {}
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000996 ~CachingWalker() override = default;
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000997
George Burgess IV400ae402016-07-20 19:51:34 +0000998 using MemorySSAWalker::getClobberingMemoryAccess;
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000999
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001000 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, unsigned &UWL) {
1001 return Walker->getClobberingMemoryAccessBase(MA, UWL, false);
1002 }
1003 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
1004 const MemoryLocation &Loc,
1005 unsigned &UWL) {
1006 return Walker->getClobberingMemoryAccessBase(MA, Loc, UWL);
1007 }
1008
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001009 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA) override {
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001010 unsigned UpwardWalkLimit = MaxCheckLimit;
1011 return getClobberingMemoryAccess(MA, UpwardWalkLimit);
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001012 }
Alina Sbirleabc8aa242019-01-07 19:22:37 +00001013 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001014 const MemoryLocation &Loc) override {
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001015 unsigned UpwardWalkLimit = MaxCheckLimit;
1016 return getClobberingMemoryAccess(MA, Loc, UpwardWalkLimit);
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001017 }
Alina Sbirleabc8aa242019-01-07 19:22:37 +00001018
1019 void invalidateInfo(MemoryAccess *MA) override {
1020 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1021 MUD->resetOptimized();
1022 }
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001023};
George Burgess IVe1100f52016-02-02 22:46:49 +00001024
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001025template <class AliasAnalysisType>
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001026class MemorySSA::SkipSelfWalker final : public MemorySSAWalker {
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001027 ClobberWalkerBase<AliasAnalysisType> *Walker;
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001028
1029public:
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001030 SkipSelfWalker(MemorySSA *M, ClobberWalkerBase<AliasAnalysisType> *W)
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001031 : MemorySSAWalker(M), Walker(W) {}
1032 ~SkipSelfWalker() override = default;
1033
1034 using MemorySSAWalker::getClobberingMemoryAccess;
1035
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001036 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, unsigned &UWL) {
1037 return Walker->getClobberingMemoryAccessBase(MA, UWL, true);
1038 }
1039 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
1040 const MemoryLocation &Loc,
1041 unsigned &UWL) {
1042 return Walker->getClobberingMemoryAccessBase(MA, Loc, UWL);
1043 }
1044
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001045 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA) override {
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001046 unsigned UpwardWalkLimit = MaxCheckLimit;
1047 return getClobberingMemoryAccess(MA, UpwardWalkLimit);
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001048 }
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001049 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001050 const MemoryLocation &Loc) override {
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001051 unsigned UpwardWalkLimit = MaxCheckLimit;
1052 return getClobberingMemoryAccess(MA, Loc, UpwardWalkLimit);
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001053 }
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001054
1055 void invalidateInfo(MemoryAccess *MA) override {
1056 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1057 MUD->resetOptimized();
1058 }
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001059};
1060
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001061} // end namespace llvm
1062
Daniel Berlin78cbd282017-02-20 22:26:03 +00001063void MemorySSA::renameSuccessorPhis(BasicBlock *BB, MemoryAccess *IncomingVal,
1064 bool RenameAllUses) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001065 // Pass through values to our successors
1066 for (const BasicBlock *S : successors(BB)) {
1067 auto It = PerBlockAccesses.find(S);
1068 // Rename the phi nodes in our successor block
1069 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1070 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +00001071 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001072 auto *Phi = cast<MemoryPhi>(&Accesses->front());
Daniel Berlin78cbd282017-02-20 22:26:03 +00001073 if (RenameAllUses) {
1074 int PhiIndex = Phi->getBasicBlockIndex(BB);
1075 assert(PhiIndex != -1 && "Incomplete phi during partial rename");
1076 Phi->setIncomingValue(PhiIndex, IncomingVal);
1077 } else
1078 Phi->addIncoming(IncomingVal, BB);
George Burgess IVe1100f52016-02-02 22:46:49 +00001079 }
Daniel Berlin78cbd282017-02-20 22:26:03 +00001080}
George Burgess IVe1100f52016-02-02 22:46:49 +00001081
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001082/// Rename a single basic block into MemorySSA form.
Daniel Berlin78cbd282017-02-20 22:26:03 +00001083/// Uses the standard SSA renaming algorithm.
1084/// \returns The new incoming value.
1085MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB, MemoryAccess *IncomingVal,
1086 bool RenameAllUses) {
1087 auto It = PerBlockAccesses.find(BB);
1088 // Skip most processing if the list is empty.
1089 if (It != PerBlockAccesses.end()) {
1090 AccessList *Accesses = It->second.get();
1091 for (MemoryAccess &L : *Accesses) {
1092 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) {
1093 if (MUD->getDefiningAccess() == nullptr || RenameAllUses)
1094 MUD->setDefiningAccess(IncomingVal);
1095 if (isa<MemoryDef>(&L))
1096 IncomingVal = &L;
1097 } else {
1098 IncomingVal = &L;
1099 }
1100 }
1101 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001102 return IncomingVal;
1103}
1104
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001105/// This is the standard SSA renaming algorithm.
George Burgess IVe1100f52016-02-02 22:46:49 +00001106///
1107/// We walk the dominator tree in preorder, renaming accesses, and then filling
1108/// in phi nodes in our successors.
1109void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
Daniel Berlin78cbd282017-02-20 22:26:03 +00001110 SmallPtrSetImpl<BasicBlock *> &Visited,
1111 bool SkipVisited, bool RenameAllUses) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001112 SmallVector<RenamePassData, 32> WorkStack;
Daniel Berlin78cbd282017-02-20 22:26:03 +00001113 // Skip everything if we already renamed this block and we are skipping.
1114 // Note: You can't sink this into the if, because we need it to occur
1115 // regardless of whether we skip blocks or not.
1116 bool AlreadyVisited = !Visited.insert(Root->getBlock()).second;
1117 if (SkipVisited && AlreadyVisited)
1118 return;
1119
1120 IncomingVal = renameBlock(Root->getBlock(), IncomingVal, RenameAllUses);
1121 renameSuccessorPhis(Root->getBlock(), IncomingVal, RenameAllUses);
George Burgess IVe1100f52016-02-02 22:46:49 +00001122 WorkStack.push_back({Root, Root->begin(), IncomingVal});
George Burgess IVe1100f52016-02-02 22:46:49 +00001123
1124 while (!WorkStack.empty()) {
1125 DomTreeNode *Node = WorkStack.back().DTN;
1126 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
1127 IncomingVal = WorkStack.back().IncomingVal;
1128
1129 if (ChildIt == Node->end()) {
1130 WorkStack.pop_back();
1131 } else {
1132 DomTreeNode *Child = *ChildIt;
1133 ++WorkStack.back().ChildIt;
1134 BasicBlock *BB = Child->getBlock();
Daniel Berlin78cbd282017-02-20 22:26:03 +00001135 // Note: You can't sink this into the if, because we need it to occur
1136 // regardless of whether we skip blocks or not.
1137 AlreadyVisited = !Visited.insert(BB).second;
1138 if (SkipVisited && AlreadyVisited) {
1139 // We already visited this during our renaming, which can happen when
1140 // being asked to rename multiple blocks. Figure out the incoming val,
1141 // which is the last def.
1142 // Incoming value can only change if there is a block def, and in that
1143 // case, it's the last block def in the list.
1144 if (auto *BlockDefs = getWritableBlockDefs(BB))
1145 IncomingVal = &*BlockDefs->rbegin();
1146 } else
1147 IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses);
1148 renameSuccessorPhis(BB, IncomingVal, RenameAllUses);
George Burgess IVe1100f52016-02-02 22:46:49 +00001149 WorkStack.push_back({Child, Child->begin(), IncomingVal});
1150 }
1151 }
1152}
1153
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001154/// This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +00001155/// unreachable blocks, and marking all other unreachable MemoryAccess's as
1156/// being uses of the live on entry definition.
1157void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
1158 assert(!DT->isReachableFromEntry(BB) &&
1159 "Reachable block found while handling unreachable blocks");
1160
Daniel Berlinfc7e6512016-07-06 05:32:05 +00001161 // Make sure phi nodes in our reachable successors end up with a
1162 // LiveOnEntryDef for our incoming edge, even though our block is forward
1163 // unreachable. We could just disconnect these blocks from the CFG fully,
1164 // but we do not right now.
1165 for (const BasicBlock *S : successors(BB)) {
1166 if (!DT->isReachableFromEntry(S))
1167 continue;
1168 auto It = PerBlockAccesses.find(S);
1169 // Rename the phi nodes in our successor block
1170 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1171 continue;
1172 AccessList *Accesses = It->second.get();
1173 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1174 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1175 }
1176
George Burgess IVe1100f52016-02-02 22:46:49 +00001177 auto It = PerBlockAccesses.find(BB);
1178 if (It == PerBlockAccesses.end())
1179 return;
1180
1181 auto &Accesses = It->second;
1182 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1183 auto Next = std::next(AI);
1184 // If we have a phi, just remove it. We are going to replace all
1185 // users with live on entry.
1186 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1187 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1188 else
1189 Accesses->erase(AI);
1190 AI = Next;
1191 }
1192}
1193
Geoff Berryb96d3b22016-06-01 21:30:40 +00001194MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001195 : AA(nullptr), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001196 SkipWalker(nullptr), NextID(0) {
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001197 // Build MemorySSA using a batch alias analysis. This reuses the internal
1198 // state that AA collects during an alias()/getModRefInfo() call. This is
1199 // safe because there are no CFG changes while building MemorySSA and can
1200 // significantly reduce the time spent by the compiler in AA, because we will
1201 // make queries about all the instructions in the Function.
1202 BatchAAResults BatchAA(*AA);
1203 buildMemorySSA(BatchAA);
1204 // Intentionally leave AA to nullptr while building so we don't accidently
1205 // use non-batch AliasAnalysis.
1206 this->AA = AA;
1207 // Also create the walker here.
1208 getWalker();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001209}
1210
George Burgess IVe1100f52016-02-02 22:46:49 +00001211MemorySSA::~MemorySSA() {
1212 // Drop all our references
1213 for (const auto &Pair : PerBlockAccesses)
1214 for (MemoryAccess &MA : *Pair.second)
1215 MA.dropAllReferences();
1216}
1217
Daniel Berlin14300262016-06-21 18:39:20 +00001218MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001219 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1220
1221 if (Res.second)
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001222 Res.first->second = llvm::make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001223 return Res.first->second.get();
1224}
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001225
Daniel Berlind602e042017-01-25 20:56:19 +00001226MemorySSA::DefsList *MemorySSA::getOrCreateDefsList(const BasicBlock *BB) {
1227 auto Res = PerBlockDefs.insert(std::make_pair(BB, nullptr));
1228
1229 if (Res.second)
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001230 Res.first->second = llvm::make_unique<DefsList>();
Daniel Berlind602e042017-01-25 20:56:19 +00001231 return Res.first->second.get();
1232}
George Burgess IVe1100f52016-02-02 22:46:49 +00001233
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001234namespace llvm {
1235
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001236/// This class is a batch walker of all MemoryUse's in the program, and points
1237/// their defining access at the thing that actually clobbers them. Because it
1238/// is a batch walker that touches everything, it does not operate like the
1239/// other walkers. This walker is basically performing a top-down SSA renaming
1240/// pass, where the version stack is used as the cache. This enables it to be
1241/// significantly more time and memory efficient than using the regular walker,
1242/// which is walking bottom-up.
1243class MemorySSA::OptimizeUses {
1244public:
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001245 OptimizeUses(MemorySSA *MSSA, CachingWalker<BatchAAResults> *Walker,
1246 BatchAAResults *BAA, DominatorTree *DT)
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001247 : MSSA(MSSA), Walker(Walker), AA(BAA), DT(DT) {}
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001248
1249 void optimizeUses();
1250
1251private:
1252 /// This represents where a given memorylocation is in the stack.
1253 struct MemlocStackInfo {
1254 // This essentially is keeping track of versions of the stack. Whenever
1255 // the stack changes due to pushes or pops, these versions increase.
1256 unsigned long StackEpoch;
1257 unsigned long PopEpoch;
1258 // This is the lower bound of places on the stack to check. It is equal to
1259 // the place the last stack walk ended.
1260 // Note: Correctness depends on this being initialized to 0, which densemap
1261 // does
1262 unsigned long LowerBound;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001263 const BasicBlock *LowerBoundBlock;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001264 // This is where the last walk for this memory location ended.
1265 unsigned long LastKill;
1266 bool LastKillValid;
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001267 Optional<AliasResult> AR;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001268 };
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001269
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001270 void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1271 SmallVectorImpl<MemoryAccess *> &,
1272 DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001273
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001274 MemorySSA *MSSA;
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001275 CachingWalker<BatchAAResults> *Walker;
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001276 BatchAAResults *AA;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001277 DominatorTree *DT;
1278};
1279
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001280} // end namespace llvm
1281
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001282/// Optimize the uses in a given block This is basically the SSA renaming
1283/// algorithm, with one caveat: We are able to use a single stack for all
1284/// MemoryUses. This is because the set of *possible* reaching MemoryDefs is
1285/// the same for every MemoryUse. The *actual* clobbering MemoryDef is just
1286/// going to be some position in that stack of possible ones.
1287///
1288/// We track the stack positions that each MemoryLocation needs
1289/// to check, and last ended at. This is because we only want to check the
1290/// things that changed since last time. The same MemoryLocation should
1291/// get clobbered by the same store (getModRefInfo does not use invariantness or
1292/// things like this, and if they start, we can modify MemoryLocOrCall to
1293/// include relevant data)
1294void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1295 const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1296 SmallVectorImpl<MemoryAccess *> &VersionStack,
1297 DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
1298
1299 /// If no accesses, nothing to do.
1300 MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
1301 if (Accesses == nullptr)
1302 return;
1303
1304 // Pop everything that doesn't dominate the current block off the stack,
1305 // increment the PopEpoch to account for this.
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001306 while (true) {
1307 assert(
1308 !VersionStack.empty() &&
1309 "Version stack should have liveOnEntry sentinel dominating everything");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001310 BasicBlock *BackBlock = VersionStack.back()->getBlock();
1311 if (DT->dominates(BackBlock, BB))
1312 break;
1313 while (VersionStack.back()->getBlock() == BackBlock)
1314 VersionStack.pop_back();
1315 ++PopEpoch;
1316 }
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001317
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001318 for (MemoryAccess &MA : *Accesses) {
1319 auto *MU = dyn_cast<MemoryUse>(&MA);
1320 if (!MU) {
1321 VersionStack.push_back(&MA);
1322 ++StackEpoch;
1323 continue;
1324 }
1325
George Burgess IV024f3d22016-08-03 19:57:02 +00001326 if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001327 MU->setDefiningAccess(MSSA->getLiveOnEntryDef(), true, None);
George Burgess IV024f3d22016-08-03 19:57:02 +00001328 continue;
1329 }
1330
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001331 MemoryLocOrCall UseMLOC(MU);
1332 auto &LocInfo = LocStackInfo[UseMLOC];
Daniel Berlin26fcea92016-08-02 20:02:21 +00001333 // If the pop epoch changed, it means we've removed stuff from top of
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001334 // stack due to changing blocks. We may have to reset the lower bound or
1335 // last kill info.
1336 if (LocInfo.PopEpoch != PopEpoch) {
1337 LocInfo.PopEpoch = PopEpoch;
1338 LocInfo.StackEpoch = StackEpoch;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001339 // If the lower bound was in something that no longer dominates us, we
1340 // have to reset it.
1341 // We can't simply track stack size, because the stack may have had
1342 // pushes/pops in the meantime.
1343 // XXX: This is non-optimal, but only is slower cases with heavily
1344 // branching dominator trees. To get the optimal number of queries would
1345 // be to make lowerbound and lastkill a per-loc stack, and pop it until
1346 // the top of that stack dominates us. This does not seem worth it ATM.
1347 // A much cheaper optimization would be to always explore the deepest
1348 // branch of the dominator tree first. This will guarantee this resets on
1349 // the smallest set of blocks.
1350 if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
Daniel Berlin1e98c042016-09-26 17:22:54 +00001351 !DT->dominates(LocInfo.LowerBoundBlock, BB)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001352 // Reset the lower bound of things to check.
1353 // TODO: Some day we should be able to reset to last kill, rather than
1354 // 0.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001355 LocInfo.LowerBound = 0;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001356 LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001357 LocInfo.LastKillValid = false;
1358 }
1359 } else if (LocInfo.StackEpoch != StackEpoch) {
1360 // If all that has changed is the StackEpoch, we only have to check the
1361 // new things on the stack, because we've checked everything before. In
1362 // this case, the lower bound of things to check remains the same.
1363 LocInfo.PopEpoch = PopEpoch;
1364 LocInfo.StackEpoch = StackEpoch;
1365 }
1366 if (!LocInfo.LastKillValid) {
1367 LocInfo.LastKill = VersionStack.size() - 1;
1368 LocInfo.LastKillValid = true;
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001369 LocInfo.AR = MayAlias;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001370 }
1371
1372 // At this point, we should have corrected last kill and LowerBound to be
1373 // in bounds.
1374 assert(LocInfo.LowerBound < VersionStack.size() &&
1375 "Lower bound out of range");
1376 assert(LocInfo.LastKill < VersionStack.size() &&
1377 "Last kill info out of range");
1378 // In any case, the new upper bound is the top of the stack.
1379 unsigned long UpperBound = VersionStack.size() - 1;
1380
1381 if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001382 LLVM_DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
1383 << *(MU->getMemoryInst()) << ")"
1384 << " because there are "
1385 << UpperBound - LocInfo.LowerBound
1386 << " stores to disambiguate\n");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001387 // Because we did not walk, LastKill is no longer valid, as this may
1388 // have been a kill.
1389 LocInfo.LastKillValid = false;
1390 continue;
1391 }
1392 bool FoundClobberResult = false;
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001393 unsigned UpwardWalkLimit = MaxCheckLimit;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001394 while (UpperBound > LocInfo.LowerBound) {
1395 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1396 // For phis, use the walker, see where we ended up, go there
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001397 MemoryAccess *Result =
1398 Walker->getClobberingMemoryAccess(MU, UpwardWalkLimit);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001399 // We are guaranteed to find it or something is wrong
1400 while (VersionStack[UpperBound] != Result) {
1401 assert(UpperBound != 0);
1402 --UpperBound;
1403 }
1404 FoundClobberResult = true;
1405 break;
1406 }
1407
1408 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
Daniel Berlindf101192016-08-03 00:01:46 +00001409 // If the lifetime of the pointer ends at this instruction, it's live on
1410 // entry.
1411 if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1412 // Reset UpperBound to liveOnEntryDef's place in the stack
1413 UpperBound = 0;
1414 FoundClobberResult = true;
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001415 LocInfo.AR = MustAlias;
Daniel Berlindf101192016-08-03 00:01:46 +00001416 break;
1417 }
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001418 ClobberAlias CA = instructionClobbersQuery(MD, MU, UseMLOC, *AA);
1419 if (CA.IsClobber) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001420 FoundClobberResult = true;
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001421 LocInfo.AR = CA.AR;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001422 break;
1423 }
1424 --UpperBound;
1425 }
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001426
1427 // Note: Phis always have AliasResult AR set to MayAlias ATM.
1428
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001429 // At the end of this loop, UpperBound is either a clobber, or lower bound
1430 // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1431 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001432 // We were last killed now by where we got to
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001433 if (MSSA->isLiveOnEntryDef(VersionStack[UpperBound]))
1434 LocInfo.AR = None;
1435 MU->setDefiningAccess(VersionStack[UpperBound], true, LocInfo.AR);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001436 LocInfo.LastKill = UpperBound;
1437 } else {
1438 // Otherwise, we checked all the new ones, and now we know we can get to
1439 // LastKill.
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001440 MU->setDefiningAccess(VersionStack[LocInfo.LastKill], true, LocInfo.AR);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001441 }
1442 LocInfo.LowerBound = VersionStack.size() - 1;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001443 LocInfo.LowerBoundBlock = BB;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001444 }
1445}
1446
1447/// Optimize uses to point to their actual clobbering definitions.
1448void MemorySSA::OptimizeUses::optimizeUses() {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001449 SmallVector<MemoryAccess *, 16> VersionStack;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001450 DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001451 VersionStack.push_back(MSSA->getLiveOnEntryDef());
1452
1453 unsigned long StackEpoch = 1;
1454 unsigned long PopEpoch = 1;
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001455 // We perform a non-recursive top-down dominator tree walk.
Daniel Berlin7ac3d742016-08-05 22:09:14 +00001456 for (const auto *DomNode : depth_first(DT->getRootNode()))
1457 optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1458 LocStackInfo);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001459}
1460
Daniel Berlin3d512a22016-08-22 19:14:30 +00001461void MemorySSA::placePHINodes(
Michael Zolotukhin67cfbaa2018-05-15 18:40:29 +00001462 const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks) {
Daniel Berlin3d512a22016-08-22 19:14:30 +00001463 // Determine where our MemoryPhi's should go
1464 ForwardIDFCalculator IDFs(*DT);
1465 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001466 SmallVector<BasicBlock *, 32> IDFBlocks;
1467 IDFs.calculate(IDFBlocks);
1468
1469 // Now place MemoryPhi nodes.
Daniel Berlind602e042017-01-25 20:56:19 +00001470 for (auto &BB : IDFBlocks)
1471 createMemoryPhi(BB);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001472}
1473
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001474void MemorySSA::buildMemorySSA(BatchAAResults &BAA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001475 // We create an access to represent "live on entry", for things like
1476 // arguments or users of globals, where the memory they use is defined before
1477 // the beginning of the function. We do not actually insert it into the IR.
1478 // We do not define a live on exit for the immediate uses, and thus our
1479 // semantics do *not* imply that something with no immediate uses can simply
1480 // be removed.
1481 BasicBlock &StartingPoint = F.getEntryBlock();
George Burgess IV612cf212018-02-27 06:43:19 +00001482 LiveOnEntryDef.reset(new MemoryDef(F.getContext(), nullptr, nullptr,
1483 &StartingPoint, NextID++));
George Burgess IVe1100f52016-02-02 22:46:49 +00001484
1485 // We maintain lists of memory accesses per-block, trading memory for time. We
1486 // could just look up the memory access for every possible instruction in the
1487 // stream.
1488 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001489 // Go through each block, figure out where defs occur, and chain together all
1490 // the accesses.
1491 for (BasicBlock &B : F) {
Daniel Berlin7898ca62016-02-07 01:52:15 +00001492 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001493 AccessList *Accesses = nullptr;
Daniel Berlind602e042017-01-25 20:56:19 +00001494 DefsList *Defs = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001495 for (Instruction &I : B) {
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001496 MemoryUseOrDef *MUD = createNewAccess(&I, &BAA);
George Burgess IVb42b7622016-03-11 19:34:03 +00001497 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001498 continue;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001499
George Burgess IVe1100f52016-02-02 22:46:49 +00001500 if (!Accesses)
1501 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001502 Accesses->push_back(MUD);
Daniel Berlind602e042017-01-25 20:56:19 +00001503 if (isa<MemoryDef>(MUD)) {
1504 InsertIntoDef = true;
1505 if (!Defs)
1506 Defs = getOrCreateDefsList(&B);
1507 Defs->push_back(*MUD);
1508 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001509 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001510 if (InsertIntoDef)
1511 DefiningBlocks.insert(&B);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001512 }
Michael Zolotukhin67cfbaa2018-05-15 18:40:29 +00001513 placePHINodes(DefiningBlocks);
George Burgess IVe1100f52016-02-02 22:46:49 +00001514
1515 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1516 // filled in with all blocks.
1517 SmallPtrSet<BasicBlock *, 16> Visited;
1518 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1519
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001520 ClobberWalkerBase<BatchAAResults> WalkerBase(this, &BAA, DT);
1521 CachingWalker<BatchAAResults> WalkerLocal(this, &WalkerBase);
1522 OptimizeUses(this, &WalkerLocal, &BAA, DT).optimizeUses();
George Burgess IV5f308972016-07-19 01:29:15 +00001523
George Burgess IVe1100f52016-02-02 22:46:49 +00001524 // Mark the uses in unreachable blocks as live on entry, so that they go
1525 // somewhere.
1526 for (auto &BB : F)
1527 if (!Visited.count(&BB))
1528 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001529}
George Burgess IVe1100f52016-02-02 22:46:49 +00001530
George Burgess IV5f308972016-07-19 01:29:15 +00001531MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1532
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001533MemorySSA::CachingWalker<AliasAnalysis> *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001534 if (Walker)
1535 return Walker.get();
1536
Alina Sbirleabc8aa242019-01-07 19:22:37 +00001537 if (!WalkerBase)
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001538 WalkerBase =
1539 llvm::make_unique<ClobberWalkerBase<AliasAnalysis>>(this, AA, DT);
Alina Sbirleabc8aa242019-01-07 19:22:37 +00001540
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001541 Walker =
1542 llvm::make_unique<CachingWalker<AliasAnalysis>>(this, WalkerBase.get());
Geoff Berryb96d3b22016-06-01 21:30:40 +00001543 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001544}
1545
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001546MemorySSAWalker *MemorySSA::getSkipSelfWalker() {
1547 if (SkipWalker)
1548 return SkipWalker.get();
1549
1550 if (!WalkerBase)
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001551 WalkerBase =
1552 llvm::make_unique<ClobberWalkerBase<AliasAnalysis>>(this, AA, DT);
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001553
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001554 SkipWalker =
1555 llvm::make_unique<SkipSelfWalker<AliasAnalysis>>(this, WalkerBase.get());
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001556 return SkipWalker.get();
1557 }
1558
1559
Daniel Berlind602e042017-01-25 20:56:19 +00001560// This is a helper function used by the creation routines. It places NewAccess
1561// into the access and defs lists for a given basic block, at the given
1562// insertion point.
1563void MemorySSA::insertIntoListsForBlock(MemoryAccess *NewAccess,
1564 const BasicBlock *BB,
1565 InsertionPlace Point) {
1566 auto *Accesses = getOrCreateAccessList(BB);
1567 if (Point == Beginning) {
1568 // If it's a phi node, it goes first, otherwise, it goes after any phi
1569 // nodes.
1570 if (isa<MemoryPhi>(NewAccess)) {
1571 Accesses->push_front(NewAccess);
1572 auto *Defs = getOrCreateDefsList(BB);
1573 Defs->push_front(*NewAccess);
1574 } else {
1575 auto AI = find_if_not(
1576 *Accesses, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1577 Accesses->insert(AI, NewAccess);
1578 if (!isa<MemoryUse>(NewAccess)) {
1579 auto *Defs = getOrCreateDefsList(BB);
1580 auto DI = find_if_not(
1581 *Defs, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1582 Defs->insert(DI, *NewAccess);
1583 }
1584 }
1585 } else {
1586 Accesses->push_back(NewAccess);
1587 if (!isa<MemoryUse>(NewAccess)) {
1588 auto *Defs = getOrCreateDefsList(BB);
1589 Defs->push_back(*NewAccess);
1590 }
1591 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001592 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001593}
1594
1595void MemorySSA::insertIntoListsBefore(MemoryAccess *What, const BasicBlock *BB,
1596 AccessList::iterator InsertPt) {
1597 auto *Accesses = getWritableBlockAccesses(BB);
1598 bool WasEnd = InsertPt == Accesses->end();
1599 Accesses->insert(AccessList::iterator(InsertPt), What);
1600 if (!isa<MemoryUse>(What)) {
1601 auto *Defs = getOrCreateDefsList(BB);
1602 // If we got asked to insert at the end, we have an easy job, just shove it
1603 // at the end. If we got asked to insert before an existing def, we also get
Zhaoshi Zhenga5531f22018-04-04 21:08:11 +00001604 // an iterator. If we got asked to insert before a use, we have to hunt for
Daniel Berlind602e042017-01-25 20:56:19 +00001605 // the next def.
1606 if (WasEnd) {
1607 Defs->push_back(*What);
1608 } else if (isa<MemoryDef>(InsertPt)) {
1609 Defs->insert(InsertPt->getDefsIterator(), *What);
1610 } else {
1611 while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt))
1612 ++InsertPt;
1613 // Either we found a def, or we are inserting at the end
1614 if (InsertPt == Accesses->end())
1615 Defs->push_back(*What);
1616 else
1617 Defs->insert(InsertPt->getDefsIterator(), *What);
1618 }
1619 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001620 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001621}
1622
George Burgess IV5676a5d2018-08-22 22:34:38 +00001623void MemorySSA::prepareForMoveTo(MemoryAccess *What, BasicBlock *BB) {
1624 // Keep it in the lookup tables, remove from the lists
1625 removeFromLists(What, false);
1626
1627 // Note that moving should implicitly invalidate the optimized state of a
1628 // MemoryUse (and Phis can't be optimized). However, it doesn't do so for a
1629 // MemoryDef.
1630 if (auto *MD = dyn_cast<MemoryDef>(What))
1631 MD->resetOptimized();
1632 What->setBlock(BB);
1633}
1634
Zhaoshi Zhenga5531f22018-04-04 21:08:11 +00001635// Move What before Where in the IR. The end result is that What will belong to
Daniel Berlin60ead052017-01-28 01:23:13 +00001636// the right lists and have the right Block set, but will not otherwise be
1637// correct. It will not have the right defining access, and if it is a def,
1638// things below it will not properly be updated.
1639void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
1640 AccessList::iterator Where) {
George Burgess IV5676a5d2018-08-22 22:34:38 +00001641 prepareForMoveTo(What, BB);
Daniel Berlin60ead052017-01-28 01:23:13 +00001642 insertIntoListsBefore(What, BB, Where);
1643}
1644
Alina Sbirlea0f533552018-07-11 22:11:46 +00001645void MemorySSA::moveTo(MemoryAccess *What, BasicBlock *BB,
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001646 InsertionPlace Point) {
Alina Sbirlea0f533552018-07-11 22:11:46 +00001647 if (isa<MemoryPhi>(What)) {
1648 assert(Point == Beginning &&
1649 "Can only move a Phi at the beginning of the block");
1650 // Update lookup table entry
1651 ValueToMemoryAccess.erase(What->getBlock());
1652 bool Inserted = ValueToMemoryAccess.insert({BB, What}).second;
1653 (void)Inserted;
1654 assert(Inserted && "Cannot move a Phi to a block that already has one");
1655 }
1656
George Burgess IV5676a5d2018-08-22 22:34:38 +00001657 prepareForMoveTo(What, BB);
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001658 insertIntoListsForBlock(What, BB, Point);
1659}
1660
Daniel Berlin14300262016-06-21 18:39:20 +00001661MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1662 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
Daniel Berlin14300262016-06-21 18:39:20 +00001663 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001664 // Phi's always are placed at the front of the block.
Daniel Berlind602e042017-01-25 20:56:19 +00001665 insertIntoListsForBlock(Phi, BB, Beginning);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001666 ValueToMemoryAccess[BB] = Phi;
Daniel Berlin14300262016-06-21 18:39:20 +00001667 return Phi;
1668}
1669
1670MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
Alina Sbirlea79800992018-09-10 20:13:01 +00001671 MemoryAccess *Definition,
1672 const MemoryUseOrDef *Template) {
Daniel Berlin14300262016-06-21 18:39:20 +00001673 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001674 MemoryUseOrDef *NewAccess = createNewAccess(I, AA, Template);
Daniel Berlin14300262016-06-21 18:39:20 +00001675 assert(
1676 NewAccess != nullptr &&
1677 "Tried to create a memory access for a non-memory touching instruction");
1678 NewAccess->setDefiningAccess(Definition);
1679 return NewAccess;
1680}
1681
Daniel Berlind952cea2017-04-07 01:28:36 +00001682// Return true if the instruction has ordering constraints.
1683// Note specifically that this only considers stores and loads
1684// because others are still considered ModRef by getModRefInfo.
1685static inline bool isOrdered(const Instruction *I) {
1686 if (auto *SI = dyn_cast<StoreInst>(I)) {
1687 if (!SI->isUnordered())
1688 return true;
1689 } else if (auto *LI = dyn_cast<LoadInst>(I)) {
1690 if (!LI->isUnordered())
1691 return true;
1692 }
1693 return false;
1694}
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001695
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001696/// Helper function to create new memory accesses
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001697template <typename AliasAnalysisType>
Alina Sbirlea79800992018-09-10 20:13:01 +00001698MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I,
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001699 AliasAnalysisType *AAP,
Alina Sbirlea79800992018-09-10 20:13:01 +00001700 const MemoryUseOrDef *Template) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001701 // The assume intrinsic has a control dependency which we model by claiming
1702 // that it writes arbitrarily. Ignore that fake memory dependency here.
1703 // FIXME: Replace this special casing with a more accurate modelling of
1704 // assume's control dependency.
1705 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1706 if (II->getIntrinsicID() == Intrinsic::assume)
1707 return nullptr;
1708
Alina Sbirlea79800992018-09-10 20:13:01 +00001709 bool Def, Use;
1710 if (Template) {
1711 Def = dyn_cast_or_null<MemoryDef>(Template) != nullptr;
1712 Use = dyn_cast_or_null<MemoryUse>(Template) != nullptr;
1713#if !defined(NDEBUG)
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001714 ModRefInfo ModRef = AAP->getModRefInfo(I, None);
Alina Sbirlea79800992018-09-10 20:13:01 +00001715 bool DefCheck, UseCheck;
1716 DefCheck = isModSet(ModRef) || isOrdered(I);
1717 UseCheck = isRefSet(ModRef);
1718 assert(Def == DefCheck && (Def || Use == UseCheck) && "Invalid template");
1719#endif
1720 } else {
1721 // Find out what affect this instruction has on memory.
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001722 ModRefInfo ModRef = AAP->getModRefInfo(I, None);
Alina Sbirlea79800992018-09-10 20:13:01 +00001723 // The isOrdered check is used to ensure that volatiles end up as defs
1724 // (atomics end up as ModRef right now anyway). Until we separate the
1725 // ordering chain from the memory chain, this enables people to see at least
1726 // some relative ordering to volatiles. Note that getClobberingMemoryAccess
1727 // will still give an answer that bypasses other volatile loads. TODO:
1728 // Separate memory aliasing and ordering into two different chains so that
1729 // we can precisely represent both "what memory will this read/write/is
1730 // clobbered by" and "what instructions can I move this past".
1731 Def = isModSet(ModRef) || isOrdered(I);
1732 Use = isRefSet(ModRef);
1733 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001734
1735 // It's possible for an instruction to not modify memory at all. During
1736 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +00001737 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +00001738 return nullptr;
1739
George Burgess IVb42b7622016-03-11 19:34:03 +00001740 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001741 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +00001742 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +00001743 else
George Burgess IVb42b7622016-03-11 19:34:03 +00001744 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
Daniel Berlin5130cc82016-07-31 21:08:20 +00001745 ValueToMemoryAccess[I] = MUD;
George Burgess IVb42b7622016-03-11 19:34:03 +00001746 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001747}
1748
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001749/// Returns true if \p Replacer dominates \p Replacee .
George Burgess IVe1100f52016-02-02 22:46:49 +00001750bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1751 const MemoryAccess *Replacee) const {
1752 if (isa<MemoryUseOrDef>(Replacee))
1753 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1754 const auto *MP = cast<MemoryPhi>(Replacee);
1755 // For a phi node, the use occurs in the predecessor block of the phi node.
1756 // Since we may occur multiple times in the phi node, we have to check each
1757 // operand to ensure Replacer dominates each operand where Replacee occurs.
1758 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +00001759 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +00001760 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1761 return false;
1762 }
1763 return true;
1764}
1765
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001766/// Properly remove \p MA from all of MemorySSA's lookup tables.
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001767void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1768 assert(MA->use_empty() &&
1769 "Trying to remove memory access that still has uses");
Daniel Berlin5c46b942016-07-19 22:49:43 +00001770 BlockNumbering.erase(MA);
George Burgess IV2cbf9732018-06-22 22:34:07 +00001771 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001772 MUD->setDefiningAccess(nullptr);
1773 // Invalidate our walker's cache if necessary
1774 if (!isa<MemoryUse>(MA))
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001775 getWalker()->invalidateInfo(MA);
George Burgess IV2cbf9732018-06-22 22:34:07 +00001776
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001777 Value *MemoryInst;
George Burgess IV2cbf9732018-06-22 22:34:07 +00001778 if (const auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001779 MemoryInst = MUD->getMemoryInst();
George Burgess IV2cbf9732018-06-22 22:34:07 +00001780 else
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001781 MemoryInst = MA->getBlock();
George Burgess IV2cbf9732018-06-22 22:34:07 +00001782
Daniel Berlin5130cc82016-07-31 21:08:20 +00001783 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1784 if (VMA->second == MA)
1785 ValueToMemoryAccess.erase(VMA);
Daniel Berlin60ead052017-01-28 01:23:13 +00001786}
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001787
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001788/// Properly remove \p MA from all of MemorySSA's lists.
Daniel Berlin60ead052017-01-28 01:23:13 +00001789///
1790/// Because of the way the intrusive list and use lists work, it is important to
1791/// do removal in the right order.
1792/// ShouldDelete defaults to true, and will cause the memory access to also be
1793/// deleted, not just removed.
1794void MemorySSA::removeFromLists(MemoryAccess *MA, bool ShouldDelete) {
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001795 BasicBlock *BB = MA->getBlock();
Daniel Berlind602e042017-01-25 20:56:19 +00001796 // The access list owns the reference, so we erase it from the non-owning list
1797 // first.
1798 if (!isa<MemoryUse>(MA)) {
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001799 auto DefsIt = PerBlockDefs.find(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001800 std::unique_ptr<DefsList> &Defs = DefsIt->second;
1801 Defs->remove(*MA);
1802 if (Defs->empty())
1803 PerBlockDefs.erase(DefsIt);
1804 }
1805
Daniel Berlin60ead052017-01-28 01:23:13 +00001806 // The erase call here will delete it. If we don't want it deleted, we call
1807 // remove instead.
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001808 auto AccessIt = PerBlockAccesses.find(BB);
Daniel Berlinada263d2016-06-20 20:21:33 +00001809 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin60ead052017-01-28 01:23:13 +00001810 if (ShouldDelete)
1811 Accesses->erase(MA);
1812 else
1813 Accesses->remove(MA);
1814
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001815 if (Accesses->empty()) {
George Burgess IVe0e6e482016-03-02 02:35:04 +00001816 PerBlockAccesses.erase(AccessIt);
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001817 BlockNumberingValid.erase(BB);
1818 }
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001819}
1820
George Burgess IVe1100f52016-02-02 22:46:49 +00001821void MemorySSA::print(raw_ostream &OS) const {
1822 MemorySSAAnnotatedWriter Writer(this);
1823 F.print(OS, &Writer);
1824}
1825
Aaron Ballman615eb472017-10-15 14:32:27 +00001826#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Daniel Berlin78cbd282017-02-20 22:26:03 +00001827LLVM_DUMP_METHOD void MemorySSA::dump() const { print(dbgs()); }
Matthias Braun8c209aa2017-01-28 02:02:38 +00001828#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001829
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001830void MemorySSA::verifyMemorySSA() const {
1831 verifyDefUses(F);
1832 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001833 verifyOrdering(F);
George Burgess IV97ec6242018-06-25 05:30:36 +00001834 verifyDominationNumbers(F);
Alina Sbirlead77edc02019-02-11 19:51:21 +00001835 // Previously, the verification used to also verify that the clobberingAccess
1836 // cached by MemorySSA is the same as the clobberingAccess found at a later
1837 // query to AA. This does not hold true in general due to the current fragility
1838 // of BasicAA which has arbitrary caps on the things it analyzes before giving
1839 // up. As a result, transformations that are correct, will lead to BasicAA
1840 // returning different Alias answers before and after that transformation.
1841 // Invalidating MemorySSA is not an option, as the results in BasicAA can be so
1842 // random, in the worst case we'd need to rebuild MemorySSA from scratch after
1843 // every transformation, which defeats the purpose of using it. For such an
1844 // example, see test4 added in D51960.
Daniel Berlin14300262016-06-21 18:39:20 +00001845}
1846
George Burgess IV97ec6242018-06-25 05:30:36 +00001847/// Verify that all of the blocks we believe to have valid domination numbers
1848/// actually have valid domination numbers.
1849void MemorySSA::verifyDominationNumbers(const Function &F) const {
1850#ifndef NDEBUG
1851 if (BlockNumberingValid.empty())
1852 return;
1853
1854 SmallPtrSet<const BasicBlock *, 16> ValidBlocks = BlockNumberingValid;
1855 for (const BasicBlock &BB : F) {
1856 if (!ValidBlocks.count(&BB))
1857 continue;
1858
1859 ValidBlocks.erase(&BB);
1860
1861 const AccessList *Accesses = getBlockAccesses(&BB);
1862 // It's correct to say an empty block has valid numbering.
1863 if (!Accesses)
1864 continue;
1865
1866 // Block numbering starts at 1.
1867 unsigned long LastNumber = 0;
1868 for (const MemoryAccess &MA : *Accesses) {
1869 auto ThisNumberIter = BlockNumbering.find(&MA);
1870 assert(ThisNumberIter != BlockNumbering.end() &&
1871 "MemoryAccess has no domination number in a valid block!");
1872
1873 unsigned long ThisNumber = ThisNumberIter->second;
1874 assert(ThisNumber > LastNumber &&
1875 "Domination numbers should be strictly increasing!");
1876 LastNumber = ThisNumber;
1877 }
1878 }
1879
1880 assert(ValidBlocks.empty() &&
1881 "All valid BasicBlocks should exist in F -- dangling pointers?");
1882#endif
1883}
1884
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001885/// Verify that the order and existence of MemoryAccesses matches the
Daniel Berlin14300262016-06-21 18:39:20 +00001886/// order and existence of memory affecting instructions.
1887void MemorySSA::verifyOrdering(Function &F) const {
George Burgess IV6a9aa022018-08-28 00:32:32 +00001888#ifndef NDEBUG
Daniel Berlin14300262016-06-21 18:39:20 +00001889 // Walk all the blocks, comparing what the lookups think and what the access
1890 // lists think, as well as the order in the blocks vs the order in the access
1891 // lists.
1892 SmallVector<MemoryAccess *, 32> ActualAccesses;
Daniel Berlind602e042017-01-25 20:56:19 +00001893 SmallVector<MemoryAccess *, 32> ActualDefs;
Daniel Berlin14300262016-06-21 18:39:20 +00001894 for (BasicBlock &B : F) {
1895 const AccessList *AL = getBlockAccesses(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001896 const auto *DL = getBlockDefs(&B);
Daniel Berlin14300262016-06-21 18:39:20 +00001897 MemoryAccess *Phi = getMemoryAccess(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001898 if (Phi) {
Daniel Berlin14300262016-06-21 18:39:20 +00001899 ActualAccesses.push_back(Phi);
Daniel Berlind602e042017-01-25 20:56:19 +00001900 ActualDefs.push_back(Phi);
1901 }
1902
Daniel Berlin14300262016-06-21 18:39:20 +00001903 for (Instruction &I : B) {
1904 MemoryAccess *MA = getMemoryAccess(&I);
Daniel Berlind602e042017-01-25 20:56:19 +00001905 assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) &&
1906 "We have memory affecting instructions "
1907 "in this block but they are not in the "
1908 "access list or defs list");
1909 if (MA) {
Daniel Berlin14300262016-06-21 18:39:20 +00001910 ActualAccesses.push_back(MA);
Daniel Berlind602e042017-01-25 20:56:19 +00001911 if (isa<MemoryDef>(MA))
1912 ActualDefs.push_back(MA);
1913 }
Daniel Berlin14300262016-06-21 18:39:20 +00001914 }
1915 // Either we hit the assert, really have no accesses, or we have both
Daniel Berlind602e042017-01-25 20:56:19 +00001916 // accesses and an access list.
1917 // Same with defs.
1918 if (!AL && !DL)
Daniel Berlin14300262016-06-21 18:39:20 +00001919 continue;
1920 assert(AL->size() == ActualAccesses.size() &&
1921 "We don't have the same number of accesses in the block as on the "
1922 "access list");
Davide Italiano6c77de02017-01-30 03:16:43 +00001923 assert((DL || ActualDefs.size() == 0) &&
1924 "Either we should have a defs list, or we should have no defs");
Daniel Berlind602e042017-01-25 20:56:19 +00001925 assert((!DL || DL->size() == ActualDefs.size()) &&
1926 "We don't have the same number of defs in the block as on the "
1927 "def list");
Daniel Berlin14300262016-06-21 18:39:20 +00001928 auto ALI = AL->begin();
1929 auto AAI = ActualAccesses.begin();
1930 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1931 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1932 ++ALI;
1933 ++AAI;
1934 }
1935 ActualAccesses.clear();
Daniel Berlind602e042017-01-25 20:56:19 +00001936 if (DL) {
1937 auto DLI = DL->begin();
1938 auto ADI = ActualDefs.begin();
1939 while (DLI != DL->end() && ADI != ActualDefs.end()) {
1940 assert(&*DLI == *ADI && "Not the same defs in the same order");
1941 ++DLI;
1942 ++ADI;
1943 }
1944 }
1945 ActualDefs.clear();
Daniel Berlin14300262016-06-21 18:39:20 +00001946 }
George Burgess IV6a9aa022018-08-28 00:32:32 +00001947#endif
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001948}
1949
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001950/// Verify the domination properties of MemorySSA by checking that each
George Burgess IVe1100f52016-02-02 22:46:49 +00001951/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001952void MemorySSA::verifyDomination(Function &F) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001953#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001954 for (BasicBlock &B : F) {
1955 // Phi nodes are attached to basic blocks
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001956 if (MemoryPhi *MP = getMemoryAccess(&B))
1957 for (const Use &U : MP->uses())
1958 assert(dominates(MP, U) && "Memory PHI does not dominate it's uses");
Daniel Berlin7af95872016-08-05 21:47:20 +00001959
George Burgess IVe1100f52016-02-02 22:46:49 +00001960 for (Instruction &I : B) {
1961 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
1962 if (!MD)
1963 continue;
1964
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001965 for (const Use &U : MD->uses())
1966 assert(dominates(MD, U) && "Memory Def does not dominate it's uses");
George Burgess IVe1100f52016-02-02 22:46:49 +00001967 }
1968 }
Daniel Berlin7af95872016-08-05 21:47:20 +00001969#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001970}
1971
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001972/// Verify the def-use lists in MemorySSA, by verifying that \p Use
George Burgess IVe1100f52016-02-02 22:46:49 +00001973/// appears in the use list of \p Def.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001974void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001975#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001976 // The live on entry use may cause us to get a NULL def here
Daniel Berlin7af95872016-08-05 21:47:20 +00001977 if (!Def)
1978 assert(isLiveOnEntryDef(Use) &&
1979 "Null def but use not point to live on entry def");
1980 else
Daniel Berlinda2f38e2016-08-11 21:26:50 +00001981 assert(is_contained(Def->users(), Use) &&
Daniel Berlin7af95872016-08-05 21:47:20 +00001982 "Did not find use in def's use list");
1983#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001984}
1985
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001986/// Verify the immediate use information, by walking all the memory
George Burgess IVe1100f52016-02-02 22:46:49 +00001987/// accesses and verifying that, for each use, it appears in the
1988/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001989void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IV6a9aa022018-08-28 00:32:32 +00001990#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001991 for (BasicBlock &B : F) {
1992 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00001993 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00001994 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
1995 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00001996 "Incomplete MemoryPhi Node");
Alina Sbirlea201d02c2018-06-20 21:06:13 +00001997 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001998 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Alina Sbirlea201d02c2018-06-20 21:06:13 +00001999 assert(find(predecessors(&B), Phi->getIncomingBlock(I)) !=
2000 pred_end(&B) &&
2001 "Incoming phi block not a block predecessor");
2002 }
Daniel Berlin14300262016-06-21 18:39:20 +00002003 }
George Burgess IVe1100f52016-02-02 22:46:49 +00002004
2005 for (Instruction &I : B) {
George Burgess IV66837ab2016-11-01 21:17:46 +00002006 if (MemoryUseOrDef *MA = getMemoryAccess(&I)) {
2007 verifyUseInDefs(MA->getDefiningAccess(), MA);
George Burgess IVe1100f52016-02-02 22:46:49 +00002008 }
2009 }
2010 }
George Burgess IV6a9aa022018-08-28 00:32:32 +00002011#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00002012}
2013
Daniel Berlin5c46b942016-07-19 22:49:43 +00002014/// Perform a local numbering on blocks so that instruction ordering can be
2015/// determined in constant time.
2016/// TODO: We currently just number in order. If we numbered by N, we could
2017/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
2018/// log2(N) sequences of mixed before and after) without needing to invalidate
2019/// the numbering.
2020void MemorySSA::renumberBlock(const BasicBlock *B) const {
2021 // The pre-increment ensures the numbers really start at 1.
2022 unsigned long CurrentNumber = 0;
2023 const AccessList *AL = getBlockAccesses(B);
2024 assert(AL != nullptr && "Asking to renumber an empty block");
2025 for (const auto &I : *AL)
2026 BlockNumbering[&I] = ++CurrentNumber;
2027 BlockNumberingValid.insert(B);
2028}
2029
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002030/// Determine, for two memory accesses in the same block,
George Burgess IVe1100f52016-02-02 22:46:49 +00002031/// whether \p Dominator dominates \p Dominatee.
2032/// \returns True if \p Dominator dominates \p Dominatee.
2033bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
2034 const MemoryAccess *Dominatee) const {
Daniel Berlin5c46b942016-07-19 22:49:43 +00002035 const BasicBlock *DominatorBlock = Dominator->getBlock();
Daniel Berlin5c46b942016-07-19 22:49:43 +00002036
Daniel Berlin19860302016-07-19 23:08:08 +00002037 assert((DominatorBlock == Dominatee->getBlock()) &&
Daniel Berlin5c46b942016-07-19 22:49:43 +00002038 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00002039 // A node dominates itself.
2040 if (Dominatee == Dominator)
2041 return true;
2042
2043 // When Dominatee is defined on function entry, it is not dominated by another
2044 // memory access.
2045 if (isLiveOnEntryDef(Dominatee))
2046 return false;
2047
2048 // When Dominator is defined on function entry, it dominates the other memory
2049 // access.
2050 if (isLiveOnEntryDef(Dominator))
2051 return true;
2052
Daniel Berlin5c46b942016-07-19 22:49:43 +00002053 if (!BlockNumberingValid.count(DominatorBlock))
2054 renumberBlock(DominatorBlock);
George Burgess IVe1100f52016-02-02 22:46:49 +00002055
Daniel Berlin5c46b942016-07-19 22:49:43 +00002056 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
2057 // All numbers start with 1
2058 assert(DominatorNum != 0 && "Block was not numbered properly");
2059 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
2060 assert(DominateeNum != 0 && "Block was not numbered properly");
2061 return DominatorNum < DominateeNum;
George Burgess IVe1100f52016-02-02 22:46:49 +00002062}
2063
George Burgess IV5f308972016-07-19 01:29:15 +00002064bool MemorySSA::dominates(const MemoryAccess *Dominator,
2065 const MemoryAccess *Dominatee) const {
2066 if (Dominator == Dominatee)
2067 return true;
2068
2069 if (isLiveOnEntryDef(Dominatee))
2070 return false;
2071
2072 if (Dominator->getBlock() != Dominatee->getBlock())
2073 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
2074 return locallyDominates(Dominator, Dominatee);
2075}
2076
Daniel Berlin2919b1c2016-08-05 21:46:52 +00002077bool MemorySSA::dominates(const MemoryAccess *Dominator,
2078 const Use &Dominatee) const {
2079 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
2080 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
2081 // The def must dominate the incoming block of the phi.
2082 if (UseBB != Dominator->getBlock())
2083 return DT->dominates(Dominator->getBlock(), UseBB);
2084 // If the UseBB and the DefBB are the same, compare locally.
2085 return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
2086 }
2087 // If it's not a PHI node use, the normal dominates can already handle it.
2088 return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
2089}
2090
George Burgess IVe1100f52016-02-02 22:46:49 +00002091const static char LiveOnEntryStr[] = "liveOnEntry";
2092
Reid Kleckner96ab8722017-05-18 17:24:10 +00002093void MemoryAccess::print(raw_ostream &OS) const {
2094 switch (getValueID()) {
2095 case MemoryPhiVal: return static_cast<const MemoryPhi *>(this)->print(OS);
2096 case MemoryDefVal: return static_cast<const MemoryDef *>(this)->print(OS);
2097 case MemoryUseVal: return static_cast<const MemoryUse *>(this)->print(OS);
2098 }
2099 llvm_unreachable("invalid value id");
2100}
2101
George Burgess IVe1100f52016-02-02 22:46:49 +00002102void MemoryDef::print(raw_ostream &OS) const {
2103 MemoryAccess *UO = getDefiningAccess();
2104
George Burgess IVaa283d82018-06-14 19:55:53 +00002105 auto printID = [&OS](MemoryAccess *A) {
2106 if (A && A->getID())
2107 OS << A->getID();
2108 else
2109 OS << LiveOnEntryStr;
2110 };
2111
George Burgess IVe1100f52016-02-02 22:46:49 +00002112 OS << getID() << " = MemoryDef(";
George Burgess IVaa283d82018-06-14 19:55:53 +00002113 printID(UO);
2114 OS << ")";
2115
2116 if (isOptimized()) {
2117 OS << "->";
2118 printID(getOptimized());
2119
2120 if (Optional<AliasResult> AR = getOptimizedAccessType())
2121 OS << " " << *AR;
2122 }
George Burgess IVe1100f52016-02-02 22:46:49 +00002123}
2124
2125void MemoryPhi::print(raw_ostream &OS) const {
2126 bool First = true;
2127 OS << getID() << " = MemoryPhi(";
2128 for (const auto &Op : operands()) {
2129 BasicBlock *BB = getIncomingBlock(Op);
2130 MemoryAccess *MA = cast<MemoryAccess>(Op);
2131 if (!First)
2132 OS << ',';
2133 else
2134 First = false;
2135
2136 OS << '{';
2137 if (BB->hasName())
2138 OS << BB->getName();
2139 else
2140 BB->printAsOperand(OS, false);
2141 OS << ',';
2142 if (unsigned ID = MA->getID())
2143 OS << ID;
2144 else
2145 OS << LiveOnEntryStr;
2146 OS << '}';
2147 }
2148 OS << ')';
2149}
2150
George Burgess IVe1100f52016-02-02 22:46:49 +00002151void MemoryUse::print(raw_ostream &OS) const {
2152 MemoryAccess *UO = getDefiningAccess();
2153 OS << "MemoryUse(";
2154 if (UO && UO->getID())
2155 OS << UO->getID();
2156 else
2157 OS << LiveOnEntryStr;
2158 OS << ')';
George Burgess IVaa283d82018-06-14 19:55:53 +00002159
2160 if (Optional<AliasResult> AR = getOptimizedAccessType())
2161 OS << " " << *AR;
George Burgess IVe1100f52016-02-02 22:46:49 +00002162}
2163
2164void MemoryAccess::dump() const {
Daniel Berlin78cbd282017-02-20 22:26:03 +00002165// Cannot completely remove virtual function even in release mode.
Aaron Ballman615eb472017-10-15 14:32:27 +00002166#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
George Burgess IVe1100f52016-02-02 22:46:49 +00002167 print(dbgs());
2168 dbgs() << "\n";
Matthias Braun8c209aa2017-01-28 02:02:38 +00002169#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00002170}
2171
Chad Rosier232e29e2016-07-06 21:20:47 +00002172char MemorySSAPrinterLegacyPass::ID = 0;
2173
2174MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
2175 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
2176}
2177
2178void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
2179 AU.setPreservesAll();
2180 AU.addRequired<MemorySSAWrapperPass>();
Chad Rosier232e29e2016-07-06 21:20:47 +00002181}
2182
2183bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
2184 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2185 MSSA.print(dbgs());
2186 if (VerifyMemorySSA)
2187 MSSA.verifyMemorySSA();
2188 return false;
2189}
2190
Chandler Carruthdab4eae2016-11-23 17:53:26 +00002191AnalysisKey MemorySSAAnalysis::Key;
George Burgess IVe1100f52016-02-02 22:46:49 +00002192
Daniel Berlin1e98c042016-09-26 17:22:54 +00002193MemorySSAAnalysis::Result MemorySSAAnalysis::run(Function &F,
2194 FunctionAnalysisManager &AM) {
Geoff Berryb96d3b22016-06-01 21:30:40 +00002195 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2196 auto &AA = AM.getResult<AAManager>(F);
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00002197 return MemorySSAAnalysis::Result(llvm::make_unique<MemorySSA>(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002198}
2199
Geoff Berryb96d3b22016-06-01 21:30:40 +00002200PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
2201 FunctionAnalysisManager &AM) {
2202 OS << "MemorySSA for function: " << F.getName() << "\n";
Geoff Berry290a13e2016-08-08 18:27:22 +00002203 AM.getResult<MemorySSAAnalysis>(F).getMSSA().print(OS);
Geoff Berryb96d3b22016-06-01 21:30:40 +00002204
2205 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00002206}
2207
Geoff Berryb96d3b22016-06-01 21:30:40 +00002208PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
2209 FunctionAnalysisManager &AM) {
Geoff Berry290a13e2016-08-08 18:27:22 +00002210 AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002211
2212 return PreservedAnalyses::all();
2213}
2214
2215char MemorySSAWrapperPass::ID = 0;
2216
2217MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
2218 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
2219}
2220
2221void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
2222
2223void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002224 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002225 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
2226 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00002227}
2228
Geoff Berryb96d3b22016-06-01 21:30:40 +00002229bool MemorySSAWrapperPass::runOnFunction(Function &F) {
2230 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2231 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2232 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002233 return false;
2234}
2235
Geoff Berryb96d3b22016-06-01 21:30:40 +00002236void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00002237
Geoff Berryb96d3b22016-06-01 21:30:40 +00002238void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002239 MSSA->print(OS);
2240}
2241
George Burgess IVe1100f52016-02-02 22:46:49 +00002242MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
2243
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002244/// Walk the use-def chains starting at \p StartingAccess and find
George Burgess IVe1100f52016-02-02 22:46:49 +00002245/// the MemoryAccess that actually clobbers Loc.
2246///
2247/// \returns our clobbering memory access
Alina Sbirleabfc779e2019-03-22 17:22:19 +00002248template <typename AliasAnalysisType>
2249MemoryAccess *
2250MemorySSA::ClobberWalkerBase<AliasAnalysisType>::getClobberingMemoryAccessBase(
Alina Sbirleaf085cc52019-03-29 21:56:09 +00002251 MemoryAccess *StartingAccess, const MemoryLocation &Loc,
2252 unsigned &UpwardWalkLimit) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002253 if (isa<MemoryPhi>(StartingAccess))
2254 return StartingAccess;
2255
2256 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
2257 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
2258 return StartingUseOrDef;
2259
2260 Instruction *I = StartingUseOrDef->getMemoryInst();
2261
2262 // Conservatively, fences are always clobbers, so don't perform the walk if we
2263 // hit a fence.
Chandler Carruth363ac682019-01-07 05:42:51 +00002264 if (!isa<CallBase>(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002265 return StartingUseOrDef;
2266
2267 UpwardsMemoryQuery Q;
2268 Q.OriginalAccess = StartingUseOrDef;
2269 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00002270 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00002271 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00002272
George Burgess IVe1100f52016-02-02 22:46:49 +00002273 // Unlike the other function, do not walk to the def of a def, because we are
2274 // handed something we already believe is the clobbering access.
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002275 // We never set SkipSelf to true in Q in this method.
George Burgess IVe1100f52016-02-02 22:46:49 +00002276 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
2277 ? StartingUseOrDef->getDefiningAccess()
2278 : StartingUseOrDef;
2279
Alina Sbirleaf085cc52019-03-29 21:56:09 +00002280 MemoryAccess *Clobber =
2281 Walker.findClobber(DefiningAccess, Q, UpwardWalkLimit);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002282 LLVM_DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2283 LLVM_DEBUG(dbgs() << *StartingUseOrDef << "\n");
2284 LLVM_DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2285 LLVM_DEBUG(dbgs() << *Clobber << "\n");
George Burgess IVe1100f52016-02-02 22:46:49 +00002286 return Clobber;
2287}
2288
Alina Sbirleabfc779e2019-03-22 17:22:19 +00002289template <typename AliasAnalysisType>
George Burgess IVe1100f52016-02-02 22:46:49 +00002290MemoryAccess *
Alina Sbirleabfc779e2019-03-22 17:22:19 +00002291MemorySSA::ClobberWalkerBase<AliasAnalysisType>::getClobberingMemoryAccessBase(
Alina Sbirleaf085cc52019-03-29 21:56:09 +00002292 MemoryAccess *MA, unsigned &UpwardWalkLimit, bool SkipSelf) {
George Burgess IV400ae402016-07-20 19:51:34 +00002293 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2294 // If this is a MemoryPhi, we can't do anything.
2295 if (!StartingAccess)
2296 return MA;
George Burgess IVe1100f52016-02-02 22:46:49 +00002297
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002298 bool IsOptimized = false;
2299
Daniel Berlincd2deac2016-10-20 20:13:45 +00002300 // If this is an already optimized use or def, return the optimized result.
Alina Sbirlead90c9f42018-03-08 18:03:14 +00002301 // Note: Currently, we store the optimized def result in a separate field,
2302 // since we can't use the defining access.
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002303 if (StartingAccess->isOptimized()) {
2304 if (!SkipSelf || !isa<MemoryDef>(StartingAccess))
2305 return StartingAccess->getOptimized();
2306 IsOptimized = true;
2307 }
Daniel Berlincd2deac2016-10-20 20:13:45 +00002308
George Burgess IV400ae402016-07-20 19:51:34 +00002309 const Instruction *I = StartingAccess->getMemoryInst();
George Burgess IV44477c62018-03-11 04:16:12 +00002310 // We can't sanely do anything with a fence, since they conservatively clobber
2311 // all memory, and have no locations to get pointers from to try to
2312 // disambiguate.
Chandler Carruth363ac682019-01-07 05:42:51 +00002313 if (!isa<CallBase>(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002314 return StartingAccess;
2315
Alina Sbirleab4d088d2018-11-13 21:12:49 +00002316 UpwardsMemoryQuery Q(I, StartingAccess);
2317
Alina Sbirleabfc779e2019-03-22 17:22:19 +00002318 if (isUseTriviallyOptimizableToLiveOnEntry(*Walker.getAA(), I)) {
George Burgess IV024f3d22016-08-03 19:57:02 +00002319 MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
George Burgess IV44477c62018-03-11 04:16:12 +00002320 StartingAccess->setOptimized(LiveOnEntry);
2321 StartingAccess->setOptimizedAccessType(None);
George Burgess IV024f3d22016-08-03 19:57:02 +00002322 return LiveOnEntry;
2323 }
2324
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002325 MemoryAccess *OptimizedAccess;
2326 if (!IsOptimized) {
2327 // Start with the thing we already think clobbers this location
2328 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
George Burgess IVe1100f52016-02-02 22:46:49 +00002329
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002330 // At this point, DefiningAccess may be the live on entry def.
2331 // If it is, we will not get a better result.
2332 if (MSSA->isLiveOnEntryDef(DefiningAccess)) {
2333 StartingAccess->setOptimized(DefiningAccess);
2334 StartingAccess->setOptimizedAccessType(None);
2335 return DefiningAccess;
2336 }
George Burgess IVe1100f52016-02-02 22:46:49 +00002337
Alina Sbirleaf085cc52019-03-29 21:56:09 +00002338 OptimizedAccess = Walker.findClobber(DefiningAccess, Q, UpwardWalkLimit);
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002339 StartingAccess->setOptimized(OptimizedAccess);
2340 if (MSSA->isLiveOnEntryDef(OptimizedAccess))
2341 StartingAccess->setOptimizedAccessType(None);
2342 else if (Q.AR == MustAlias)
2343 StartingAccess->setOptimizedAccessType(MustAlias);
2344 } else
2345 OptimizedAccess = StartingAccess->getOptimized();
2346
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002347 LLVM_DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002348 LLVM_DEBUG(dbgs() << *StartingAccess << "\n");
2349 LLVM_DEBUG(dbgs() << "Optimized Memory SSA clobber for " << *I << " is ");
2350 LLVM_DEBUG(dbgs() << *OptimizedAccess << "\n");
Alina Sbirlead90c9f42018-03-08 18:03:14 +00002351
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002352 MemoryAccess *Result;
2353 if (SkipSelf && isa<MemoryPhi>(OptimizedAccess) &&
Alina Sbirleaf085cc52019-03-29 21:56:09 +00002354 isa<MemoryDef>(StartingAccess) && UpwardWalkLimit) {
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002355 assert(isa<MemoryDef>(Q.OriginalAccess));
2356 Q.SkipSelfAccess = true;
Alina Sbirleaf085cc52019-03-29 21:56:09 +00002357 Result = Walker.findClobber(OptimizedAccess, Q, UpwardWalkLimit);
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002358 } else
2359 Result = OptimizedAccess;
2360
2361 LLVM_DEBUG(dbgs() << "Result Memory SSA clobber [SkipSelf = " << SkipSelf);
2362 LLVM_DEBUG(dbgs() << "] for " << *I << " is " << *Result << "\n");
George Burgess IVe1100f52016-02-02 22:46:49 +00002363
2364 return Result;
2365}
2366
George Burgess IVe1100f52016-02-02 22:46:49 +00002367MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002368DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002369 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2370 return Use->getDefiningAccess();
2371 return MA;
2372}
2373
2374MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
George Burgess IV013fd732016-10-28 19:22:46 +00002375 MemoryAccess *StartingAccess, const MemoryLocation &) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002376 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2377 return Use->getDefiningAccess();
2378 return StartingAccess;
2379}
Reid Kleckner96ab8722017-05-18 17:24:10 +00002380
2381void MemoryPhi::deleteMe(DerivedUser *Self) {
2382 delete static_cast<MemoryPhi *>(Self);
2383}
2384
2385void MemoryDef::deleteMe(DerivedUser *Self) {
2386 delete static_cast<MemoryDef *>(Self);
2387}
2388
2389void MemoryUse::deleteMe(DerivedUser *Self) {
2390 delete static_cast<MemoryUse *>(Self);
2391}