blob: d41fe15fa077d8f3737763b212d65c86ee241558 [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>
Alina Sbirlea63e97fa2019-07-31 17:41:04 +000052#include <cstdlib>
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000053#include <iterator>
54#include <memory>
55#include <utility>
56
57using namespace llvm;
George Burgess IVe1100f52016-02-02 22:46:49 +000058
59#define DEBUG_TYPE "memoryssa"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000060
Geoff Berryefb0dd12016-06-14 21:19:40 +000061INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
Geoff Berryb96d3b22016-06-01 21:30:40 +000062 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000063INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
64INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Geoff Berryefb0dd12016-06-14 21:19:40 +000065INITIALIZE_PASS_END(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
66 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000067
Chad Rosier232e29e2016-07-06 21:20:47 +000068INITIALIZE_PASS_BEGIN(MemorySSAPrinterLegacyPass, "print-memoryssa",
69 "Memory SSA Printer", false, false)
70INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
71INITIALIZE_PASS_END(MemorySSAPrinterLegacyPass, "print-memoryssa",
72 "Memory SSA Printer", false, false)
73
Daniel Berlinc43aa5a2016-08-02 16:24:03 +000074static cl::opt<unsigned> MaxCheckLimit(
75 "memssa-check-limit", cl::Hidden, cl::init(100),
76 cl::desc("The maximum number of stores/phis MemorySSA"
77 "will consider trying to walk past (default = 100)"));
78
Alina Sbirleacc2e8cc2018-08-15 17:34:55 +000079// Always verify MemorySSA if expensive checking is enabled.
80#ifdef EXPENSIVE_CHECKS
81bool llvm::VerifyMemorySSA = true;
82#else
83bool llvm::VerifyMemorySSA = false;
84#endif
Alina Sbirlea4fd1f262019-04-23 20:59:44 +000085/// Enables memory ssa as a dependency for loop passes in legacy pass manager.
86cl::opt<bool> llvm::EnableMSSALoopDependency(
Alina Sbirleaccb18622019-09-03 21:20:46 +000087 "enable-mssa-loop-dependency", cl::Hidden, cl::init(false),
Alina Sbirlea4fd1f262019-04-23 20:59:44 +000088 cl::desc("Enable MemorySSA dependency for loop pass manager"));
89
Alina Sbirleacc2e8cc2018-08-15 17:34:55 +000090static cl::opt<bool, true>
91 VerifyMemorySSAX("verify-memoryssa", cl::location(VerifyMemorySSA),
92 cl::Hidden, cl::desc("Enable verification of MemorySSA."));
Chad Rosier232e29e2016-07-06 21:20:47 +000093
George Burgess IVe1100f52016-02-02 22:46:49 +000094namespace llvm {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000095
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000096/// An assembly annotator class to print Memory SSA information in
George Burgess IVe1100f52016-02-02 22:46:49 +000097/// comments.
98class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
99 friend class MemorySSA;
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000100
George Burgess IVe1100f52016-02-02 22:46:49 +0000101 const MemorySSA *MSSA;
102
103public:
104 MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
105
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000106 void emitBasicBlockStartAnnot(const BasicBlock *BB,
107 formatted_raw_ostream &OS) override {
George Burgess IVe1100f52016-02-02 22:46:49 +0000108 if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
109 OS << "; " << *MA << "\n";
110 }
111
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000112 void emitInstructionAnnot(const Instruction *I,
113 formatted_raw_ostream &OS) override {
George Burgess IVe1100f52016-02-02 22:46:49 +0000114 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
115 OS << "; " << *MA << "\n";
116 }
117};
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000118
119} // end namespace llvm
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000120
George Burgess IV5f308972016-07-19 01:29:15 +0000121namespace {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000122
Daniel Berlindff31de2016-08-02 21:57:52 +0000123/// Our current alias analysis API differentiates heavily between calls and
124/// non-calls, and functions called on one usually assert on the other.
125/// This class encapsulates the distinction to simplify other code that wants
126/// "Memory affecting instructions and related data" to use as a key.
127/// For example, this class is used as a densemap key in the use optimizer.
128class MemoryLocOrCall {
129public:
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000130 bool IsCall = false;
131
Daniel Berlindff31de2016-08-02 21:57:52 +0000132 MemoryLocOrCall(MemoryUseOrDef *MUD)
133 : MemoryLocOrCall(MUD->getMemoryInst()) {}
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000134 MemoryLocOrCall(const MemoryUseOrDef *MUD)
135 : MemoryLocOrCall(MUD->getMemoryInst()) {}
Daniel Berlindff31de2016-08-02 21:57:52 +0000136
137 MemoryLocOrCall(Instruction *Inst) {
Chandler Carruth363ac682019-01-07 05:42:51 +0000138 if (auto *C = dyn_cast<CallBase>(Inst)) {
Daniel Berlindff31de2016-08-02 21:57:52 +0000139 IsCall = true;
Chandler Carruth363ac682019-01-07 05:42:51 +0000140 Call = C;
Daniel Berlindff31de2016-08-02 21:57:52 +0000141 } else {
142 IsCall = false;
143 // There is no such thing as a memorylocation for a fence inst, and it is
144 // unique in that regard.
145 if (!isa<FenceInst>(Inst))
146 Loc = MemoryLocation::get(Inst);
147 }
148 }
149
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000150 explicit MemoryLocOrCall(const MemoryLocation &Loc) : Loc(Loc) {}
Daniel Berlindff31de2016-08-02 21:57:52 +0000151
Chandler Carruth363ac682019-01-07 05:42:51 +0000152 const CallBase *getCall() const {
Daniel Berlindff31de2016-08-02 21:57:52 +0000153 assert(IsCall);
Chandler Carruth363ac682019-01-07 05:42:51 +0000154 return Call;
Daniel Berlindff31de2016-08-02 21:57:52 +0000155 }
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000156
Daniel Berlindff31de2016-08-02 21:57:52 +0000157 MemoryLocation getLoc() const {
158 assert(!IsCall);
159 return Loc;
160 }
161
162 bool operator==(const MemoryLocOrCall &Other) const {
163 if (IsCall != Other.IsCall)
164 return false;
165
George Burgess IV3588fd42018-03-29 00:54:39 +0000166 if (!IsCall)
167 return Loc == Other.Loc;
168
Chandler Carruth363ac682019-01-07 05:42:51 +0000169 if (Call->getCalledValue() != Other.Call->getCalledValue())
George Burgess IV3588fd42018-03-29 00:54:39 +0000170 return false;
171
Chandler Carruth363ac682019-01-07 05:42:51 +0000172 return Call->arg_size() == Other.Call->arg_size() &&
173 std::equal(Call->arg_begin(), Call->arg_end(),
174 Other.Call->arg_begin());
Daniel Berlindff31de2016-08-02 21:57:52 +0000175 }
176
177private:
Daniel Berlinf5361132016-10-22 04:15:41 +0000178 union {
Chandler Carruth363ac682019-01-07 05:42:51 +0000179 const CallBase *Call;
Daniel Berlind602e042017-01-25 20:56:19 +0000180 MemoryLocation Loc;
Daniel Berlinf5361132016-10-22 04:15:41 +0000181 };
Daniel Berlindff31de2016-08-02 21:57:52 +0000182};
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000183
184} // end anonymous namespace
Daniel Berlindff31de2016-08-02 21:57:52 +0000185
186namespace llvm {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000187
Daniel Berlindff31de2016-08-02 21:57:52 +0000188template <> struct DenseMapInfo<MemoryLocOrCall> {
189 static inline MemoryLocOrCall getEmptyKey() {
190 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getEmptyKey());
191 }
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000192
Daniel Berlindff31de2016-08-02 21:57:52 +0000193 static inline MemoryLocOrCall getTombstoneKey() {
194 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getTombstoneKey());
195 }
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000196
Daniel Berlindff31de2016-08-02 21:57:52 +0000197 static unsigned getHashValue(const MemoryLocOrCall &MLOC) {
George Burgess IV3588fd42018-03-29 00:54:39 +0000198 if (!MLOC.IsCall)
199 return hash_combine(
200 MLOC.IsCall,
201 DenseMapInfo<MemoryLocation>::getHashValue(MLOC.getLoc()));
202
203 hash_code hash =
204 hash_combine(MLOC.IsCall, DenseMapInfo<const Value *>::getHashValue(
Chandler Carruth363ac682019-01-07 05:42:51 +0000205 MLOC.getCall()->getCalledValue()));
George Burgess IV3588fd42018-03-29 00:54:39 +0000206
Chandler Carruth363ac682019-01-07 05:42:51 +0000207 for (const Value *Arg : MLOC.getCall()->args())
George Burgess IV3588fd42018-03-29 00:54:39 +0000208 hash = hash_combine(hash, DenseMapInfo<const Value *>::getHashValue(Arg));
209 return hash;
Daniel Berlindff31de2016-08-02 21:57:52 +0000210 }
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000211
Daniel Berlindff31de2016-08-02 21:57:52 +0000212 static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS) {
213 return LHS == RHS;
214 }
215};
Daniel Berlindf101192016-08-03 00:01:46 +0000216
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000217} // end namespace llvm
218
George Burgess IV82e355c2016-08-03 19:39:54 +0000219/// This does one-way checks to see if Use could theoretically be hoisted above
220/// MayClobber. This will not check the other way around.
221///
222/// This assumes that, for the purposes of MemorySSA, Use comes directly after
223/// MayClobber, with no potentially clobbering operations in between them.
224/// (Where potentially clobbering ops are memory barriers, aliased stores, etc.)
Alina Sbirleaca741a82017-12-22 19:54:03 +0000225static bool areLoadsReorderable(const LoadInst *Use,
226 const LoadInst *MayClobber) {
George Burgess IV82e355c2016-08-03 19:39:54 +0000227 bool VolatileUse = Use->isVolatile();
228 bool VolatileClobber = MayClobber->isVolatile();
229 // Volatile operations may never be reordered with other volatile operations.
230 if (VolatileUse && VolatileClobber)
Alina Sbirleaca741a82017-12-22 19:54:03 +0000231 return false;
232 // Otherwise, volatile doesn't matter here. From the language reference:
233 // 'optimizers may change the order of volatile operations relative to
234 // non-volatile operations.'"
George Burgess IV82e355c2016-08-03 19:39:54 +0000235
236 // If a load is seq_cst, it cannot be moved above other loads. If its ordering
237 // is weaker, it can be moved above other loads. We just need to be sure that
238 // MayClobber isn't an acquire load, because loads can't be moved above
239 // acquire loads.
240 //
241 // Note that this explicitly *does* allow the free reordering of monotonic (or
242 // weaker) loads of the same address.
243 bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent;
244 bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(),
245 AtomicOrdering::Acquire);
Alina Sbirleaca741a82017-12-22 19:54:03 +0000246 return !(SeqCstUse || MayClobberIsAcquire);
George Burgess IV82e355c2016-08-03 19:39:54 +0000247}
248
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000249namespace {
250
251struct ClobberAlias {
252 bool IsClobber;
253 Optional<AliasResult> AR;
254};
255
256} // end anonymous namespace
257
258// Return a pair of {IsClobber (bool), AR (AliasResult)}. It relies on AR being
259// ignored if IsClobber = false.
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000260template <typename AliasAnalysisType>
261static ClobberAlias
262instructionClobbersQuery(const MemoryDef *MD, const MemoryLocation &UseLoc,
263 const Instruction *UseInst, AliasAnalysisType &AA) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000264 Instruction *DefInst = MD->getMemoryInst();
265 assert(DefInst && "Defining instruction not actually an instruction");
Chandler Carruth363ac682019-01-07 05:42:51 +0000266 const auto *UseCall = dyn_cast<CallBase>(UseInst);
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000267 Optional<AliasResult> AR;
George Burgess IV5f308972016-07-19 01:29:15 +0000268
Daniel Berlindf101192016-08-03 00:01:46 +0000269 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
270 // These intrinsics will show up as affecting memory, but they are just
George Burgess IVff08c802018-08-10 05:14:43 +0000271 // markers, mostly.
272 //
273 // FIXME: We probably don't actually want MemorySSA to model these at all
274 // (including creating MemoryAccesses for them): we just end up inventing
275 // clobbers where they don't really exist at all. Please see D43269 for
276 // context.
Daniel Berlindf101192016-08-03 00:01:46 +0000277 switch (II->getIntrinsicID()) {
278 case Intrinsic::lifetime_start:
Chandler Carruth363ac682019-01-07 05:42:51 +0000279 if (UseCall)
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000280 return {false, NoAlias};
281 AR = AA.alias(MemoryLocation(II->getArgOperand(1)), UseLoc);
George Burgess IVff08c802018-08-10 05:14:43 +0000282 return {AR != NoAlias, AR};
Daniel Berlindf101192016-08-03 00:01:46 +0000283 case Intrinsic::lifetime_end:
284 case Intrinsic::invariant_start:
285 case Intrinsic::invariant_end:
286 case Intrinsic::assume:
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000287 return {false, NoAlias};
Daniel Berlindf101192016-08-03 00:01:46 +0000288 default:
289 break;
290 }
291 }
292
Chandler Carruth363ac682019-01-07 05:42:51 +0000293 if (UseCall) {
294 ModRefInfo I = AA.getModRefInfo(DefInst, UseCall);
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000295 AR = isMustSet(I) ? MustAlias : MayAlias;
296 return {isModOrRefSet(I), AR};
Hans Wennborg70e22d12017-11-21 18:00:01 +0000297 }
George Burgess IV82e355c2016-08-03 19:39:54 +0000298
Alina Sbirleaca741a82017-12-22 19:54:03 +0000299 if (auto *DefLoad = dyn_cast<LoadInst>(DefInst))
300 if (auto *UseLoad = dyn_cast<LoadInst>(UseInst))
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000301 return {!areLoadsReorderable(UseLoad, DefLoad), MayAlias};
George Burgess IV82e355c2016-08-03 19:39:54 +0000302
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000303 ModRefInfo I = AA.getModRefInfo(DefInst, UseLoc);
304 AR = isMustSet(I) ? MustAlias : MayAlias;
305 return {isModSet(I), AR};
Daniel Berlindff31de2016-08-02 21:57:52 +0000306}
307
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000308template <typename AliasAnalysisType>
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000309static ClobberAlias instructionClobbersQuery(MemoryDef *MD,
310 const MemoryUseOrDef *MU,
311 const MemoryLocOrCall &UseMLOC,
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000312 AliasAnalysisType &AA) {
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000313 // FIXME: This is a temporary hack to allow a single instructionClobbersQuery
314 // to exist while MemoryLocOrCall is pushed through places.
315 if (UseMLOC.IsCall)
316 return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(),
317 AA);
318 return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(),
319 AA);
320}
321
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000322// Return true when MD may alias MU, return false otherwise.
Daniel Berlindcb004f2017-03-02 23:06:46 +0000323bool MemorySSAUtil::defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
324 AliasAnalysis &AA) {
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000325 return instructionClobbersQuery(MD, MU, MemoryLocOrCall(MU), AA).IsClobber;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000326}
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000327
328namespace {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000329
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000330struct UpwardsMemoryQuery {
331 // True if our original query started off as a call
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000332 bool IsCall = false;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000333 // The pointer location we started the query with. This will be empty if
334 // IsCall is true.
335 MemoryLocation StartingLoc;
336 // This is the instruction we were querying about.
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000337 const Instruction *Inst = nullptr;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000338 // The MemoryAccess we actually got called with, used to test local domination
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000339 const MemoryAccess *OriginalAccess = nullptr;
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000340 Optional<AliasResult> AR = MayAlias;
Alina Sbirleaf7230202019-01-07 18:40:27 +0000341 bool SkipSelfAccess = false;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000342
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000343 UpwardsMemoryQuery() = default;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000344
345 UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
Chandler Carruth363ac682019-01-07 05:42:51 +0000346 : IsCall(isa<CallBase>(Inst)), Inst(Inst), OriginalAccess(Access) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000347 if (!IsCall)
348 StartingLoc = MemoryLocation::get(Inst);
349 }
350};
351
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000352} // end anonymous namespace
353
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000354static bool lifetimeEndsAt(MemoryDef *MD, const MemoryLocation &Loc,
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000355 BatchAAResults &AA) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000356 Instruction *Inst = MD->getMemoryInst();
357 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
358 switch (II->getIntrinsicID()) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000359 case Intrinsic::lifetime_end:
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000360 return AA.alias(MemoryLocation(II->getArgOperand(1)), Loc) == MustAlias;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000361 default:
362 return false;
363 }
364 }
365 return false;
366}
367
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000368template <typename AliasAnalysisType>
369static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysisType &AA,
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000370 const Instruction *I) {
371 // If the memory can't be changed, then loads of the memory can't be
372 // clobbered.
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000373 return isa<LoadInst>(I) && (I->getMetadata(LLVMContext::MD_invariant_load) ||
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000374 AA.pointsToConstantMemory(MemoryLocation(
375 cast<LoadInst>(I)->getPointerOperand())));
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000376}
377
George Burgess IV5f308972016-07-19 01:29:15 +0000378/// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
379/// inbetween `Start` and `ClobberAt` can clobbers `Start`.
380///
381/// This is meant to be as simple and self-contained as possible. Because it
382/// uses no cache, etc., it can be relatively expensive.
383///
384/// \param Start The MemoryAccess that we want to walk from.
385/// \param ClobberAt A clobber for Start.
386/// \param StartLoc The MemoryLocation for Start.
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000387/// \param MSSA The MemorySSA instance that Start and ClobberAt belong to.
George Burgess IV5f308972016-07-19 01:29:15 +0000388/// \param Query The UpwardsMemoryQuery we used for our search.
389/// \param AA The AliasAnalysis we used for our search.
Alina Sbirlea65f385d2018-09-07 23:51:41 +0000390/// \param AllowImpreciseClobber Always false, unless we do relaxed verify.
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000391
392template <typename AliasAnalysisType>
Alina Sbirlead77edc02019-02-11 19:51:21 +0000393LLVM_ATTRIBUTE_UNUSED static void
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000394checkClobberSanity(const MemoryAccess *Start, MemoryAccess *ClobberAt,
George Burgess IV5f308972016-07-19 01:29:15 +0000395 const MemoryLocation &StartLoc, const MemorySSA &MSSA,
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000396 const UpwardsMemoryQuery &Query, AliasAnalysisType &AA,
Alina Sbirlea65f385d2018-09-07 23:51:41 +0000397 bool AllowImpreciseClobber = false) {
George Burgess IV5f308972016-07-19 01:29:15 +0000398 assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
399
400 if (MSSA.isLiveOnEntryDef(Start)) {
401 assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
402 "liveOnEntry must clobber itself");
403 return;
404 }
405
George Burgess IV5f308972016-07-19 01:29:15 +0000406 bool FoundClobber = false;
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000407 DenseSet<ConstMemoryAccessPair> VisitedPhis;
408 SmallVector<ConstMemoryAccessPair, 8> Worklist;
George Burgess IV5f308972016-07-19 01:29:15 +0000409 Worklist.emplace_back(Start, StartLoc);
410 // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
411 // is found, complain.
412 while (!Worklist.empty()) {
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000413 auto MAP = Worklist.pop_back_val();
George Burgess IV5f308972016-07-19 01:29:15 +0000414 // All we care about is that nothing from Start to ClobberAt clobbers Start.
415 // We learn nothing from revisiting nodes.
416 if (!VisitedPhis.insert(MAP).second)
417 continue;
418
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000419 for (const auto *MA : def_chain(MAP.first)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000420 if (MA == ClobberAt) {
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000421 if (const auto *MD = dyn_cast<MemoryDef>(MA)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000422 // instructionClobbersQuery isn't essentially free, so don't use `|=`,
423 // since it won't let us short-circuit.
424 //
425 // Also, note that this can't be hoisted out of the `Worklist` loop,
426 // since MD may only act as a clobber for 1 of N MemoryLocations.
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000427 FoundClobber = FoundClobber || MSSA.isLiveOnEntryDef(MD);
428 if (!FoundClobber) {
429 ClobberAlias CA =
430 instructionClobbersQuery(MD, MAP.second, Query.Inst, AA);
431 if (CA.IsClobber) {
432 FoundClobber = true;
433 // Not used: CA.AR;
434 }
435 }
George Burgess IV5f308972016-07-19 01:29:15 +0000436 }
437 break;
438 }
439
440 // We should never hit liveOnEntry, unless it's the clobber.
441 assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
442
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000443 if (const auto *MD = dyn_cast<MemoryDef>(MA)) {
Alina Sbirlea5bce4d52018-08-29 22:38:51 +0000444 // If Start is a Def, skip self.
445 if (MD == Start)
446 continue;
447
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000448 assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA)
449 .IsClobber &&
George Burgess IV5f308972016-07-19 01:29:15 +0000450 "Found clobber before reaching ClobberAt!");
451 continue;
452 }
453
Alina Sbirlea5bce4d52018-08-29 22:38:51 +0000454 if (const auto *MU = dyn_cast<MemoryUse>(MA)) {
Alina Sbirlea6edcc9e2018-08-29 23:20:29 +0000455 (void)MU;
Alina Sbirlea5bce4d52018-08-29 22:38:51 +0000456 assert (MU == Start &&
457 "Can only find use in def chain if Start is a use");
458 continue;
459 }
460
George Burgess IV5f308972016-07-19 01:29:15 +0000461 assert(isa<MemoryPhi>(MA));
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000462 Worklist.append(
463 upward_defs_begin({const_cast<MemoryAccess *>(MA), MAP.second}),
464 upward_defs_end());
George Burgess IV5f308972016-07-19 01:29:15 +0000465 }
466 }
467
Alina Sbirlea65f385d2018-09-07 23:51:41 +0000468 // If the verify is done following an optimization, it's possible that
469 // ClobberAt was a conservative clobbering, that we can now infer is not a
470 // true clobbering access. Don't fail the verify if that's the case.
471 // We do have accesses that claim they're optimized, but could be optimized
472 // further. Updating all these can be expensive, so allow it for now (FIXME).
473 if (AllowImpreciseClobber)
474 return;
475
George Burgess IV5f308972016-07-19 01:29:15 +0000476 // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
477 // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
478 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
479 "ClobberAt never acted as a clobber");
480}
481
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000482namespace {
483
George Burgess IV5f308972016-07-19 01:29:15 +0000484/// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
485/// in one class.
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000486template <class AliasAnalysisType> class ClobberWalker {
George Burgess IV5f308972016-07-19 01:29:15 +0000487 /// Save a few bytes by using unsigned instead of size_t.
488 using ListIndex = unsigned;
489
490 /// Represents a span of contiguous MemoryDefs, potentially ending in a
491 /// MemoryPhi.
492 struct DefPath {
493 MemoryLocation Loc;
494 // Note that, because we always walk in reverse, Last will always dominate
495 // First. Also note that First and Last are inclusive.
496 MemoryAccess *First;
497 MemoryAccess *Last;
George Burgess IV5f308972016-07-19 01:29:15 +0000498 Optional<ListIndex> Previous;
499
500 DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
501 Optional<ListIndex> Previous)
502 : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
503
504 DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
505 Optional<ListIndex> Previous)
506 : DefPath(Loc, Init, Init, Previous) {}
507 };
508
509 const MemorySSA &MSSA;
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000510 AliasAnalysisType &AA;
George Burgess IV5f308972016-07-19 01:29:15 +0000511 DominatorTree &DT;
George Burgess IV5f308972016-07-19 01:29:15 +0000512 UpwardsMemoryQuery *Query;
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000513 unsigned *UpwardWalkLimit;
George Burgess IV5f308972016-07-19 01:29:15 +0000514
515 // Phi optimization bookkeeping
516 SmallVector<DefPath, 32> Paths;
517 DenseSet<ConstMemoryAccessPair> VisitedPhis;
George Burgess IV5f308972016-07-19 01:29:15 +0000518
George Burgess IV5f308972016-07-19 01:29:15 +0000519 /// Find the nearest def or phi that `From` can legally be optimized to.
Daniel Berlind0420312017-04-01 09:01:12 +0000520 const MemoryAccess *getWalkTarget(const MemoryPhi *From) const {
George Burgess IV5f308972016-07-19 01:29:15 +0000521 assert(From->getNumOperands() && "Phi with no operands?");
522
523 BasicBlock *BB = From->getBlock();
George Burgess IV5f308972016-07-19 01:29:15 +0000524 MemoryAccess *Result = MSSA.getLiveOnEntryDef();
525 DomTreeNode *Node = DT.getNode(BB);
526 while ((Node = Node->getIDom())) {
Daniel Berlin7500c562017-04-01 08:59:45 +0000527 auto *Defs = MSSA.getBlockDefs(Node->getBlock());
528 if (Defs)
Daniel Berlind0420312017-04-01 09:01:12 +0000529 return &*Defs->rbegin();
George Burgess IV5f308972016-07-19 01:29:15 +0000530 }
George Burgess IV5f308972016-07-19 01:29:15 +0000531 return Result;
532 }
533
534 /// Result of calling walkToPhiOrClobber.
535 struct UpwardsWalkResult {
536 /// The "Result" of the walk. Either a clobber, the last thing we walked, or
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000537 /// both. Include alias info when clobber found.
George Burgess IV5f308972016-07-19 01:29:15 +0000538 MemoryAccess *Result;
539 bool IsKnownClobber;
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000540 Optional<AliasResult> AR;
George Burgess IV5f308972016-07-19 01:29:15 +0000541 };
542
543 /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
544 /// This will update Desc.Last as it walks. It will (optionally) also stop at
545 /// StopAt.
546 ///
547 /// This does not test for whether StopAt is a clobber
Daniel Berlind0420312017-04-01 09:01:12 +0000548 UpwardsWalkResult
Alina Sbirleaf7230202019-01-07 18:40:27 +0000549 walkToPhiOrClobber(DefPath &Desc, const MemoryAccess *StopAt = nullptr,
550 const MemoryAccess *SkipStopAt = nullptr) const {
George Burgess IV5f308972016-07-19 01:29:15 +0000551 assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
Alina Sbirleac8d6e042019-03-29 22:55:59 +0000552 assert(UpwardWalkLimit && "Need a valid walk limit");
Alina Sbirlea57769382019-04-12 18:48:46 +0000553 bool LimitAlreadyReached = false;
554 // (*UpwardWalkLimit) may be 0 here, due to the loop in tryOptimizePhi. Set
555 // it to 1. This will not do any alias() calls. It either returns in the
556 // first iteration in the loop below, or is set back to 0 if all def chains
557 // are free of MemoryDefs.
558 if (!*UpwardWalkLimit) {
559 *UpwardWalkLimit = 1;
560 LimitAlreadyReached = true;
561 }
George Burgess IV5f308972016-07-19 01:29:15 +0000562
563 for (MemoryAccess *Current : def_chain(Desc.Last)) {
564 Desc.Last = Current;
Alina Sbirleaf7230202019-01-07 18:40:27 +0000565 if (Current == StopAt || Current == SkipStopAt)
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000566 return {Current, false, MayAlias};
George Burgess IV5f308972016-07-19 01:29:15 +0000567
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000568 if (auto *MD = dyn_cast<MemoryDef>(Current)) {
569 if (MSSA.isLiveOnEntryDef(MD))
570 return {MD, true, MustAlias};
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000571
572 if (!--*UpwardWalkLimit)
573 return {Current, true, MayAlias};
574
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000575 ClobberAlias CA =
576 instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA);
577 if (CA.IsClobber)
578 return {MD, true, CA.AR};
579 }
George Burgess IV5f308972016-07-19 01:29:15 +0000580 }
581
Alina Sbirlea57769382019-04-12 18:48:46 +0000582 if (LimitAlreadyReached)
583 *UpwardWalkLimit = 0;
584
George Burgess IV5f308972016-07-19 01:29:15 +0000585 assert(isa<MemoryPhi>(Desc.Last) &&
586 "Ended at a non-clobber that's not a phi?");
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000587 return {Desc.Last, false, MayAlias};
George Burgess IV5f308972016-07-19 01:29:15 +0000588 }
589
590 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
591 ListIndex PriorNode) {
592 auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),
593 upward_defs_end());
594 for (const MemoryAccessPair &P : UpwardDefs) {
595 PausedSearches.push_back(Paths.size());
596 Paths.emplace_back(P.second, P.first, PriorNode);
597 }
598 }
599
600 /// Represents a search that terminated after finding a clobber. This clobber
601 /// may or may not be present in the path of defs from LastNode..SearchStart,
602 /// since it may have been retrieved from cache.
603 struct TerminatedPath {
604 MemoryAccess *Clobber;
605 ListIndex LastNode;
606 };
607
608 /// Get an access that keeps us from optimizing to the given phi.
609 ///
610 /// PausedSearches is an array of indices into the Paths array. Its incoming
611 /// value is the indices of searches that stopped at the last phi optimization
612 /// target. It's left in an unspecified state.
613 ///
614 /// If this returns None, NewPaused is a vector of searches that terminated
615 /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
George Burgess IV14633b52016-08-03 01:22:19 +0000616 Optional<TerminatedPath>
Daniel Berlind0420312017-04-01 09:01:12 +0000617 getBlockingAccess(const MemoryAccess *StopWhere,
George Burgess IV5f308972016-07-19 01:29:15 +0000618 SmallVectorImpl<ListIndex> &PausedSearches,
619 SmallVectorImpl<ListIndex> &NewPaused,
620 SmallVectorImpl<TerminatedPath> &Terminated) {
621 assert(!PausedSearches.empty() && "No searches to continue?");
622
623 // BFS vs DFS really doesn't make a difference here, so just do a DFS with
624 // PausedSearches as our stack.
625 while (!PausedSearches.empty()) {
626 ListIndex PathIndex = PausedSearches.pop_back_val();
627 DefPath &Node = Paths[PathIndex];
628
629 // If we've already visited this path with this MemoryLocation, we don't
630 // need to do so again.
631 //
632 // NOTE: That we just drop these paths on the ground makes caching
633 // behavior sporadic. e.g. given a diamond:
634 // A
635 // B C
636 // D
637 //
638 // ...If we walk D, B, A, C, we'll only cache the result of phi
639 // optimization for A, B, and D; C will be skipped because it dies here.
640 // This arguably isn't the worst thing ever, since:
641 // - We generally query things in a top-down order, so if we got below D
642 // without needing cache entries for {C, MemLoc}, then chances are
643 // that those cache entries would end up ultimately unused.
644 // - We still cache things for A, so C only needs to walk up a bit.
645 // If this behavior becomes problematic, we can fix without a ton of extra
646 // work.
647 if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
648 continue;
649
Alina Sbirleaf7230202019-01-07 18:40:27 +0000650 const MemoryAccess *SkipStopWhere = nullptr;
651 if (Query->SkipSelfAccess && Node.Loc == Query->StartingLoc) {
652 assert(isa<MemoryDef>(Query->OriginalAccess));
653 SkipStopWhere = Query->OriginalAccess;
654 }
655
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000656 UpwardsWalkResult Res = walkToPhiOrClobber(Node,
657 /*StopAt=*/StopWhere,
Alina Sbirleaf7230202019-01-07 18:40:27 +0000658 /*SkipStopAt=*/SkipStopWhere);
George Burgess IV5f308972016-07-19 01:29:15 +0000659 if (Res.IsKnownClobber) {
Alina Sbirleaf7230202019-01-07 18:40:27 +0000660 assert(Res.Result != StopWhere && Res.Result != SkipStopWhere);
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000661
George Burgess IV5f308972016-07-19 01:29:15 +0000662 // If this wasn't a cache hit, we hit a clobber when walking. That's a
663 // failure.
George Burgess IV14633b52016-08-03 01:22:19 +0000664 TerminatedPath Term{Res.Result, PathIndex};
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000665 if (!MSSA.dominates(Res.Result, StopWhere))
George Burgess IV14633b52016-08-03 01:22:19 +0000666 return Term;
George Burgess IV5f308972016-07-19 01:29:15 +0000667
668 // Otherwise, it's a valid thing to potentially optimize to.
George Burgess IV14633b52016-08-03 01:22:19 +0000669 Terminated.push_back(Term);
George Burgess IV5f308972016-07-19 01:29:15 +0000670 continue;
671 }
672
Alina Sbirleaf7230202019-01-07 18:40:27 +0000673 if (Res.Result == StopWhere || Res.Result == SkipStopWhere) {
George Burgess IV5f308972016-07-19 01:29:15 +0000674 // We've hit our target. Save this path off for if we want to continue
Alina Sbirleaf7230202019-01-07 18:40:27 +0000675 // walking. If we are in the mode of skipping the OriginalAccess, and
676 // we've reached back to the OriginalAccess, do not save path, we've
677 // just looped back to self.
678 if (Res.Result != SkipStopWhere)
679 NewPaused.push_back(PathIndex);
George Burgess IV5f308972016-07-19 01:29:15 +0000680 continue;
681 }
682
683 assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
684 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
685 }
686
687 return None;
688 }
689
690 template <typename T, typename Walker>
691 struct generic_def_path_iterator
692 : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
693 std::forward_iterator_tag, T *> {
Hans Wennborg5519cb22019-03-25 09:27:42 +0000694 generic_def_path_iterator() {}
George Burgess IV5f308972016-07-19 01:29:15 +0000695 generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
696
697 T &operator*() const { return curNode(); }
698
699 generic_def_path_iterator &operator++() {
700 N = curNode().Previous;
701 return *this;
702 }
703
704 bool operator==(const generic_def_path_iterator &O) const {
705 if (N.hasValue() != O.N.hasValue())
706 return false;
707 return !N.hasValue() || *N == *O.N;
708 }
709
710 private:
711 T &curNode() const { return W->Paths[*N]; }
712
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000713 Walker *W = nullptr;
714 Optional<ListIndex> N = None;
George Burgess IV5f308972016-07-19 01:29:15 +0000715 };
716
717 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
718 using const_def_path_iterator =
719 generic_def_path_iterator<const DefPath, const ClobberWalker>;
720
721 iterator_range<def_path_iterator> def_path(ListIndex From) {
722 return make_range(def_path_iterator(this, From), def_path_iterator());
723 }
724
725 iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
726 return make_range(const_def_path_iterator(this, From),
727 const_def_path_iterator());
728 }
729
730 struct OptznResult {
731 /// The path that contains our result.
732 TerminatedPath PrimaryClobber;
733 /// The paths that we can legally cache back from, but that aren't
734 /// necessarily the result of the Phi optimization.
735 SmallVector<TerminatedPath, 4> OtherClobbers;
736 };
737
738 ListIndex defPathIndex(const DefPath &N) const {
739 // The assert looks nicer if we don't need to do &N
740 const DefPath *NP = &N;
741 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
742 "Out of bounds DefPath!");
743 return NP - &Paths.front();
744 }
745
746 /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
747 /// that act as legal clobbers. Note that this won't return *all* clobbers.
748 ///
749 /// Phi optimization algorithm tl;dr:
750 /// - Find the earliest def/phi, A, we can optimize to
751 /// - Find if all paths from the starting memory access ultimately reach A
752 /// - If not, optimization isn't possible.
753 /// - Otherwise, walk from A to another clobber or phi, A'.
754 /// - If A' is a def, we're done.
755 /// - If A' is a phi, try to optimize it.
756 ///
757 /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
758 /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
759 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
760 const MemoryLocation &Loc) {
761 assert(Paths.empty() && VisitedPhis.empty() &&
762 "Reset the optimization state.");
763
764 Paths.emplace_back(Loc, Start, Phi, None);
765 // Stores how many "valid" optimization nodes we had prior to calling
766 // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
767 auto PriorPathsSize = Paths.size();
768
769 SmallVector<ListIndex, 16> PausedSearches;
770 SmallVector<ListIndex, 8> NewPaused;
771 SmallVector<TerminatedPath, 4> TerminatedPaths;
772
773 addSearches(Phi, PausedSearches, 0);
774
775 // Moves the TerminatedPath with the "most dominated" Clobber to the end of
776 // Paths.
777 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
778 assert(!Paths.empty() && "Need a path to move");
George Burgess IV5f308972016-07-19 01:29:15 +0000779 auto Dom = Paths.begin();
780 for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
781 if (!MSSA.dominates(I->Clobber, Dom->Clobber))
782 Dom = I;
783 auto Last = Paths.end() - 1;
784 if (Last != Dom)
785 std::iter_swap(Last, Dom);
786 };
787
788 MemoryPhi *Current = Phi;
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000789 while (true) {
George Burgess IV5f308972016-07-19 01:29:15 +0000790 assert(!MSSA.isLiveOnEntryDef(Current) &&
791 "liveOnEntry wasn't treated as a clobber?");
792
Daniel Berlind0420312017-04-01 09:01:12 +0000793 const auto *Target = getWalkTarget(Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000794 // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
795 // optimization for the prior phi.
796 assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
797 return MSSA.dominates(P.Clobber, Target);
798 }));
799
800 // FIXME: This is broken, because the Blocker may be reported to be
801 // liveOnEntry, and we'll happily wait for that to disappear (read: never)
George Burgess IV7f414b92016-08-22 23:40:01 +0000802 // For the moment, this is fine, since we do nothing with blocker info.
George Burgess IV14633b52016-08-03 01:22:19 +0000803 if (Optional<TerminatedPath> Blocker = getBlockingAccess(
George Burgess IV5f308972016-07-19 01:29:15 +0000804 Target, PausedSearches, NewPaused, TerminatedPaths)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000805
806 // Find the node we started at. We can't search based on N->Last, since
807 // we may have gone around a loop with a different MemoryLocation.
George Burgess IV14633b52016-08-03 01:22:19 +0000808 auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
George Burgess IV5f308972016-07-19 01:29:15 +0000809 return defPathIndex(N) < PriorPathsSize;
810 });
811 assert(Iter != def_path_iterator());
812
813 DefPath &CurNode = *Iter;
814 assert(CurNode.Last == Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000815
816 // Two things:
817 // A. We can't reliably cache all of NewPaused back. Consider a case
818 // where we have two paths in NewPaused; one of which can't optimize
819 // above this phi, whereas the other can. If we cache the second path
820 // back, we'll end up with suboptimal cache entries. We can handle
821 // cases like this a bit better when we either try to find all
822 // clobbers that block phi optimization, or when our cache starts
823 // supporting unfinished searches.
824 // B. We can't reliably cache TerminatedPaths back here without doing
825 // extra checks; consider a case like:
826 // T
827 // / \
828 // D C
829 // \ /
830 // S
831 // Where T is our target, C is a node with a clobber on it, D is a
832 // diamond (with a clobber *only* on the left or right node, N), and
833 // S is our start. Say we walk to D, through the node opposite N
834 // (read: ignoring the clobber), and see a cache entry in the top
835 // node of D. That cache entry gets put into TerminatedPaths. We then
836 // walk up to C (N is later in our worklist), find the clobber, and
837 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
838 // the bottom part of D to the cached clobber, ignoring the clobber
839 // in N. Again, this problem goes away if we start tracking all
840 // blockers for a given phi optimization.
841 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
842 return {Result, {}};
843 }
844
845 // If there's nothing left to search, then all paths led to valid clobbers
846 // that we got from our cache; pick the nearest to the start, and allow
847 // the rest to be cached back.
848 if (NewPaused.empty()) {
849 MoveDominatedPathToEnd(TerminatedPaths);
850 TerminatedPath Result = TerminatedPaths.pop_back_val();
851 return {Result, std::move(TerminatedPaths)};
852 }
853
854 MemoryAccess *DefChainEnd = nullptr;
855 SmallVector<TerminatedPath, 4> Clobbers;
856 for (ListIndex Paused : NewPaused) {
857 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
858 if (WR.IsKnownClobber)
859 Clobbers.push_back({WR.Result, Paused});
860 else
861 // Micro-opt: If we hit the end of the chain, save it.
862 DefChainEnd = WR.Result;
863 }
864
865 if (!TerminatedPaths.empty()) {
866 // If we couldn't find the dominating phi/liveOnEntry in the above loop,
867 // do it now.
868 if (!DefChainEnd)
Daniel Berlind0420312017-04-01 09:01:12 +0000869 for (auto *MA : def_chain(const_cast<MemoryAccess *>(Target)))
George Burgess IV5f308972016-07-19 01:29:15 +0000870 DefChainEnd = MA;
871
872 // If any of the terminated paths don't dominate the phi we'll try to
873 // optimize, we need to figure out what they are and quit.
874 const BasicBlock *ChainBB = DefChainEnd->getBlock();
875 for (const TerminatedPath &TP : TerminatedPaths) {
876 // Because we know that DefChainEnd is as "high" as we can go, we
877 // don't need local dominance checks; BB dominance is sufficient.
878 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
879 Clobbers.push_back(TP);
880 }
881 }
882
883 // If we have clobbers in the def chain, find the one closest to Current
884 // and quit.
885 if (!Clobbers.empty()) {
886 MoveDominatedPathToEnd(Clobbers);
887 TerminatedPath Result = Clobbers.pop_back_val();
888 return {Result, std::move(Clobbers)};
889 }
890
891 assert(all_of(NewPaused,
892 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
893
894 // Because liveOnEntry is a clobber, this must be a phi.
895 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
896
897 PriorPathsSize = Paths.size();
898 PausedSearches.clear();
899 for (ListIndex I : NewPaused)
900 addSearches(DefChainPhi, PausedSearches, I);
901 NewPaused.clear();
902
903 Current = DefChainPhi;
904 }
905 }
906
George Burgess IV5f308972016-07-19 01:29:15 +0000907 void verifyOptResult(const OptznResult &R) const {
908 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
909 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
910 }));
911 }
912
913 void resetPhiOptznState() {
914 Paths.clear();
915 VisitedPhis.clear();
916 }
917
918public:
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000919 ClobberWalker(const MemorySSA &MSSA, AliasAnalysisType &AA, DominatorTree &DT)
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000920 : MSSA(MSSA), AA(AA), DT(DT) {}
George Burgess IV5f308972016-07-19 01:29:15 +0000921
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000922 AliasAnalysisType *getAA() { return &AA; }
George Burgess IV5f308972016-07-19 01:29:15 +0000923 /// Finds the nearest clobber for the given query, optimizing phis if
924 /// possible.
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000925 MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q,
926 unsigned &UpWalkLimit) {
George Burgess IV5f308972016-07-19 01:29:15 +0000927 Query = &Q;
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000928 UpwardWalkLimit = &UpWalkLimit;
929 // Starting limit must be > 0.
930 if (!UpWalkLimit)
931 UpWalkLimit++;
George Burgess IV5f308972016-07-19 01:29:15 +0000932
933 MemoryAccess *Current = Start;
934 // This walker pretends uses don't exist. If we're handed one, silently grab
935 // its def. (This has the nice side-effect of ensuring we never cache uses)
936 if (auto *MU = dyn_cast<MemoryUse>(Start))
937 Current = MU->getDefiningAccess();
938
939 DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
940 // Fast path for the overly-common case (no crazy phi optimization
941 // necessary)
942 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000943 MemoryAccess *Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000944 if (WalkResult.IsKnownClobber) {
George Burgess IV93ea19b2016-07-24 07:03:49 +0000945 Result = WalkResult.Result;
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000946 Q.AR = WalkResult.AR;
George Burgess IV93ea19b2016-07-24 07:03:49 +0000947 } else {
948 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
949 Current, Q.StartingLoc);
950 verifyOptResult(OptRes);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000951 resetPhiOptznState();
952 Result = OptRes.PrimaryClobber.Clobber;
George Burgess IV5f308972016-07-19 01:29:15 +0000953 }
954
George Burgess IV5f308972016-07-19 01:29:15 +0000955#ifdef EXPENSIVE_CHECKS
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000956 if (!Q.SkipSelfAccess && *UpwardWalkLimit > 0)
Alina Sbirleae41f4b32019-01-10 21:47:15 +0000957 checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000958#endif
George Burgess IV93ea19b2016-07-24 07:03:49 +0000959 return Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000960 }
961};
962
963struct RenamePassData {
964 DomTreeNode *DTN;
965 DomTreeNode::const_iterator ChildIt;
966 MemoryAccess *IncomingVal;
967
968 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
969 MemoryAccess *M)
970 : DTN(D), ChildIt(It), IncomingVal(M) {}
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000971
George Burgess IV5f308972016-07-19 01:29:15 +0000972 void swap(RenamePassData &RHS) {
973 std::swap(DTN, RHS.DTN);
974 std::swap(ChildIt, RHS.ChildIt);
975 std::swap(IncomingVal, RHS.IncomingVal);
976 }
977};
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000978
979} // end anonymous namespace
George Burgess IV5f308972016-07-19 01:29:15 +0000980
981namespace llvm {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000982
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000983template <class AliasAnalysisType> class MemorySSA::ClobberWalkerBase {
984 ClobberWalker<AliasAnalysisType> Walker;
Alina Sbirleabc8aa242019-01-07 19:22:37 +0000985 MemorySSA *MSSA;
986
987public:
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000988 ClobberWalkerBase(MemorySSA *M, AliasAnalysisType *A, DominatorTree *D)
Alina Sbirleabc8aa242019-01-07 19:22:37 +0000989 : Walker(*M, *A, *D), MSSA(M) {}
990
991 MemoryAccess *getClobberingMemoryAccessBase(MemoryAccess *,
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000992 const MemoryLocation &,
993 unsigned &);
994 // Third argument (bool), defines whether the clobber search should skip the
Alina Sbirleabc8aa242019-01-07 19:22:37 +0000995 // original queried access. If true, there will be a follow-up query searching
996 // for a clobber access past "self". Note that the Optimized access is not
997 // updated if a new clobber is found by this SkipSelf search. If this
998 // additional query becomes heavily used we may decide to cache the result.
999 // Walker instantiations will decide how to set the SkipSelf bool.
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001000 MemoryAccess *getClobberingMemoryAccessBase(MemoryAccess *, unsigned &, bool);
Alina Sbirleabc8aa242019-01-07 19:22:37 +00001001};
1002
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001003/// A MemorySSAWalker that does AA walks to disambiguate accesses. It no
George Burgess IV45f263d2018-05-26 02:28:55 +00001004/// longer does caching on its own, but the name has been retained for the
1005/// moment.
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001006template <class AliasAnalysisType>
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001007class MemorySSA::CachingWalker final : public MemorySSAWalker {
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001008 ClobberWalkerBase<AliasAnalysisType> *Walker;
George Burgess IV5f308972016-07-19 01:29:15 +00001009
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001010public:
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001011 CachingWalker(MemorySSA *M, ClobberWalkerBase<AliasAnalysisType> *W)
Alina Sbirleabc8aa242019-01-07 19:22:37 +00001012 : MemorySSAWalker(M), Walker(W) {}
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001013 ~CachingWalker() override = default;
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001014
George Burgess IV400ae402016-07-20 19:51:34 +00001015 using MemorySSAWalker::getClobberingMemoryAccess;
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001016
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001017 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, unsigned &UWL) {
1018 return Walker->getClobberingMemoryAccessBase(MA, UWL, false);
1019 }
1020 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
1021 const MemoryLocation &Loc,
1022 unsigned &UWL) {
1023 return Walker->getClobberingMemoryAccessBase(MA, Loc, UWL);
1024 }
1025
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001026 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA) override {
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001027 unsigned UpwardWalkLimit = MaxCheckLimit;
1028 return getClobberingMemoryAccess(MA, UpwardWalkLimit);
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001029 }
Alina Sbirleabc8aa242019-01-07 19:22:37 +00001030 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001031 const MemoryLocation &Loc) override {
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001032 unsigned UpwardWalkLimit = MaxCheckLimit;
1033 return getClobberingMemoryAccess(MA, Loc, UpwardWalkLimit);
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001034 }
Alina Sbirleabc8aa242019-01-07 19:22:37 +00001035
1036 void invalidateInfo(MemoryAccess *MA) override {
1037 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1038 MUD->resetOptimized();
1039 }
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001040};
George Burgess IVe1100f52016-02-02 22:46:49 +00001041
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001042template <class AliasAnalysisType>
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001043class MemorySSA::SkipSelfWalker final : public MemorySSAWalker {
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001044 ClobberWalkerBase<AliasAnalysisType> *Walker;
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001045
1046public:
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001047 SkipSelfWalker(MemorySSA *M, ClobberWalkerBase<AliasAnalysisType> *W)
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001048 : MemorySSAWalker(M), Walker(W) {}
1049 ~SkipSelfWalker() override = default;
1050
1051 using MemorySSAWalker::getClobberingMemoryAccess;
1052
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001053 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, unsigned &UWL) {
1054 return Walker->getClobberingMemoryAccessBase(MA, UWL, true);
1055 }
1056 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
1057 const MemoryLocation &Loc,
1058 unsigned &UWL) {
1059 return Walker->getClobberingMemoryAccessBase(MA, Loc, UWL);
1060 }
1061
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001062 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA) override {
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001063 unsigned UpwardWalkLimit = MaxCheckLimit;
1064 return getClobberingMemoryAccess(MA, UpwardWalkLimit);
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001065 }
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001066 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001067 const MemoryLocation &Loc) override {
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001068 unsigned UpwardWalkLimit = MaxCheckLimit;
1069 return getClobberingMemoryAccess(MA, Loc, UpwardWalkLimit);
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001070 }
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001071
1072 void invalidateInfo(MemoryAccess *MA) override {
1073 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1074 MUD->resetOptimized();
1075 }
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001076};
1077
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001078} // end namespace llvm
1079
Daniel Berlin78cbd282017-02-20 22:26:03 +00001080void MemorySSA::renameSuccessorPhis(BasicBlock *BB, MemoryAccess *IncomingVal,
1081 bool RenameAllUses) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001082 // Pass through values to our successors
1083 for (const BasicBlock *S : successors(BB)) {
1084 auto It = PerBlockAccesses.find(S);
1085 // Rename the phi nodes in our successor block
1086 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1087 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +00001088 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001089 auto *Phi = cast<MemoryPhi>(&Accesses->front());
Daniel Berlin78cbd282017-02-20 22:26:03 +00001090 if (RenameAllUses) {
Alina Sbirlea3d037692019-08-30 23:02:53 +00001091 bool ReplacementDone = false;
1092 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1093 if (Phi->getIncomingBlock(I) == BB) {
1094 Phi->setIncomingValue(I, IncomingVal);
1095 ReplacementDone = true;
1096 }
1097 (void) ReplacementDone;
1098 assert(ReplacementDone && "Incomplete phi during partial rename");
Daniel Berlin78cbd282017-02-20 22:26:03 +00001099 } else
1100 Phi->addIncoming(IncomingVal, BB);
George Burgess IVe1100f52016-02-02 22:46:49 +00001101 }
Daniel Berlin78cbd282017-02-20 22:26:03 +00001102}
George Burgess IVe1100f52016-02-02 22:46:49 +00001103
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001104/// Rename a single basic block into MemorySSA form.
Daniel Berlin78cbd282017-02-20 22:26:03 +00001105/// Uses the standard SSA renaming algorithm.
1106/// \returns The new incoming value.
1107MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB, MemoryAccess *IncomingVal,
1108 bool RenameAllUses) {
1109 auto It = PerBlockAccesses.find(BB);
1110 // Skip most processing if the list is empty.
1111 if (It != PerBlockAccesses.end()) {
1112 AccessList *Accesses = It->second.get();
1113 for (MemoryAccess &L : *Accesses) {
1114 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) {
1115 if (MUD->getDefiningAccess() == nullptr || RenameAllUses)
1116 MUD->setDefiningAccess(IncomingVal);
1117 if (isa<MemoryDef>(&L))
1118 IncomingVal = &L;
1119 } else {
1120 IncomingVal = &L;
1121 }
1122 }
1123 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001124 return IncomingVal;
1125}
1126
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001127/// This is the standard SSA renaming algorithm.
George Burgess IVe1100f52016-02-02 22:46:49 +00001128///
1129/// We walk the dominator tree in preorder, renaming accesses, and then filling
1130/// in phi nodes in our successors.
1131void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
Daniel Berlin78cbd282017-02-20 22:26:03 +00001132 SmallPtrSetImpl<BasicBlock *> &Visited,
1133 bool SkipVisited, bool RenameAllUses) {
Alina Sbirlea0363c3b2019-05-02 23:41:58 +00001134 assert(Root && "Trying to rename accesses in an unreachable block");
1135
George Burgess IVe1100f52016-02-02 22:46:49 +00001136 SmallVector<RenamePassData, 32> WorkStack;
Daniel Berlin78cbd282017-02-20 22:26:03 +00001137 // Skip everything if we already renamed this block and we are skipping.
1138 // Note: You can't sink this into the if, because we need it to occur
1139 // regardless of whether we skip blocks or not.
1140 bool AlreadyVisited = !Visited.insert(Root->getBlock()).second;
1141 if (SkipVisited && AlreadyVisited)
1142 return;
1143
1144 IncomingVal = renameBlock(Root->getBlock(), IncomingVal, RenameAllUses);
1145 renameSuccessorPhis(Root->getBlock(), IncomingVal, RenameAllUses);
George Burgess IVe1100f52016-02-02 22:46:49 +00001146 WorkStack.push_back({Root, Root->begin(), IncomingVal});
George Burgess IVe1100f52016-02-02 22:46:49 +00001147
1148 while (!WorkStack.empty()) {
1149 DomTreeNode *Node = WorkStack.back().DTN;
1150 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
1151 IncomingVal = WorkStack.back().IncomingVal;
1152
1153 if (ChildIt == Node->end()) {
1154 WorkStack.pop_back();
1155 } else {
1156 DomTreeNode *Child = *ChildIt;
1157 ++WorkStack.back().ChildIt;
1158 BasicBlock *BB = Child->getBlock();
Daniel Berlin78cbd282017-02-20 22:26:03 +00001159 // Note: You can't sink this into the if, because we need it to occur
1160 // regardless of whether we skip blocks or not.
1161 AlreadyVisited = !Visited.insert(BB).second;
1162 if (SkipVisited && AlreadyVisited) {
1163 // We already visited this during our renaming, which can happen when
1164 // being asked to rename multiple blocks. Figure out the incoming val,
1165 // which is the last def.
1166 // Incoming value can only change if there is a block def, and in that
1167 // case, it's the last block def in the list.
1168 if (auto *BlockDefs = getWritableBlockDefs(BB))
1169 IncomingVal = &*BlockDefs->rbegin();
1170 } else
1171 IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses);
1172 renameSuccessorPhis(BB, IncomingVal, RenameAllUses);
George Burgess IVe1100f52016-02-02 22:46:49 +00001173 WorkStack.push_back({Child, Child->begin(), IncomingVal});
1174 }
1175 }
1176}
1177
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001178/// This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +00001179/// unreachable blocks, and marking all other unreachable MemoryAccess's as
1180/// being uses of the live on entry definition.
1181void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
1182 assert(!DT->isReachableFromEntry(BB) &&
1183 "Reachable block found while handling unreachable blocks");
1184
Daniel Berlinfc7e6512016-07-06 05:32:05 +00001185 // Make sure phi nodes in our reachable successors end up with a
1186 // LiveOnEntryDef for our incoming edge, even though our block is forward
1187 // unreachable. We could just disconnect these blocks from the CFG fully,
1188 // but we do not right now.
1189 for (const BasicBlock *S : successors(BB)) {
1190 if (!DT->isReachableFromEntry(S))
1191 continue;
1192 auto It = PerBlockAccesses.find(S);
1193 // Rename the phi nodes in our successor block
1194 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1195 continue;
1196 AccessList *Accesses = It->second.get();
1197 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1198 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1199 }
1200
George Burgess IVe1100f52016-02-02 22:46:49 +00001201 auto It = PerBlockAccesses.find(BB);
1202 if (It == PerBlockAccesses.end())
1203 return;
1204
1205 auto &Accesses = It->second;
1206 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1207 auto Next = std::next(AI);
1208 // If we have a phi, just remove it. We are going to replace all
1209 // users with live on entry.
1210 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1211 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1212 else
1213 Accesses->erase(AI);
1214 AI = Next;
1215 }
1216}
1217
Geoff Berryb96d3b22016-06-01 21:30:40 +00001218MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001219 : AA(nullptr), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001220 SkipWalker(nullptr), NextID(0) {
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001221 // Build MemorySSA using a batch alias analysis. This reuses the internal
1222 // state that AA collects during an alias()/getModRefInfo() call. This is
1223 // safe because there are no CFG changes while building MemorySSA and can
1224 // significantly reduce the time spent by the compiler in AA, because we will
1225 // make queries about all the instructions in the Function.
1226 BatchAAResults BatchAA(*AA);
1227 buildMemorySSA(BatchAA);
1228 // Intentionally leave AA to nullptr while building so we don't accidently
1229 // use non-batch AliasAnalysis.
1230 this->AA = AA;
1231 // Also create the walker here.
1232 getWalker();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001233}
1234
George Burgess IVe1100f52016-02-02 22:46:49 +00001235MemorySSA::~MemorySSA() {
1236 // Drop all our references
1237 for (const auto &Pair : PerBlockAccesses)
1238 for (MemoryAccess &MA : *Pair.second)
1239 MA.dropAllReferences();
1240}
1241
Daniel Berlin14300262016-06-21 18:39:20 +00001242MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001243 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1244
1245 if (Res.second)
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001246 Res.first->second = std::make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001247 return Res.first->second.get();
1248}
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001249
Daniel Berlind602e042017-01-25 20:56:19 +00001250MemorySSA::DefsList *MemorySSA::getOrCreateDefsList(const BasicBlock *BB) {
1251 auto Res = PerBlockDefs.insert(std::make_pair(BB, nullptr));
1252
1253 if (Res.second)
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001254 Res.first->second = std::make_unique<DefsList>();
Daniel Berlind602e042017-01-25 20:56:19 +00001255 return Res.first->second.get();
1256}
George Burgess IVe1100f52016-02-02 22:46:49 +00001257
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001258namespace llvm {
1259
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001260/// This class is a batch walker of all MemoryUse's in the program, and points
1261/// their defining access at the thing that actually clobbers them. Because it
1262/// is a batch walker that touches everything, it does not operate like the
1263/// other walkers. This walker is basically performing a top-down SSA renaming
1264/// pass, where the version stack is used as the cache. This enables it to be
1265/// significantly more time and memory efficient than using the regular walker,
1266/// which is walking bottom-up.
1267class MemorySSA::OptimizeUses {
1268public:
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001269 OptimizeUses(MemorySSA *MSSA, CachingWalker<BatchAAResults> *Walker,
1270 BatchAAResults *BAA, DominatorTree *DT)
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001271 : MSSA(MSSA), Walker(Walker), AA(BAA), DT(DT) {}
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001272
1273 void optimizeUses();
1274
1275private:
1276 /// This represents where a given memorylocation is in the stack.
1277 struct MemlocStackInfo {
1278 // This essentially is keeping track of versions of the stack. Whenever
1279 // the stack changes due to pushes or pops, these versions increase.
1280 unsigned long StackEpoch;
1281 unsigned long PopEpoch;
1282 // This is the lower bound of places on the stack to check. It is equal to
1283 // the place the last stack walk ended.
1284 // Note: Correctness depends on this being initialized to 0, which densemap
1285 // does
1286 unsigned long LowerBound;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001287 const BasicBlock *LowerBoundBlock;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001288 // This is where the last walk for this memory location ended.
1289 unsigned long LastKill;
1290 bool LastKillValid;
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001291 Optional<AliasResult> AR;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001292 };
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001293
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001294 void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1295 SmallVectorImpl<MemoryAccess *> &,
1296 DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001297
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001298 MemorySSA *MSSA;
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001299 CachingWalker<BatchAAResults> *Walker;
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001300 BatchAAResults *AA;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001301 DominatorTree *DT;
1302};
1303
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001304} // end namespace llvm
1305
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001306/// Optimize the uses in a given block This is basically the SSA renaming
1307/// algorithm, with one caveat: We are able to use a single stack for all
1308/// MemoryUses. This is because the set of *possible* reaching MemoryDefs is
1309/// the same for every MemoryUse. The *actual* clobbering MemoryDef is just
1310/// going to be some position in that stack of possible ones.
1311///
1312/// We track the stack positions that each MemoryLocation needs
1313/// to check, and last ended at. This is because we only want to check the
1314/// things that changed since last time. The same MemoryLocation should
1315/// get clobbered by the same store (getModRefInfo does not use invariantness or
1316/// things like this, and if they start, we can modify MemoryLocOrCall to
1317/// include relevant data)
1318void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1319 const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1320 SmallVectorImpl<MemoryAccess *> &VersionStack,
1321 DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
1322
1323 /// If no accesses, nothing to do.
1324 MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
1325 if (Accesses == nullptr)
1326 return;
1327
1328 // Pop everything that doesn't dominate the current block off the stack,
1329 // increment the PopEpoch to account for this.
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001330 while (true) {
1331 assert(
1332 !VersionStack.empty() &&
1333 "Version stack should have liveOnEntry sentinel dominating everything");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001334 BasicBlock *BackBlock = VersionStack.back()->getBlock();
1335 if (DT->dominates(BackBlock, BB))
1336 break;
1337 while (VersionStack.back()->getBlock() == BackBlock)
1338 VersionStack.pop_back();
1339 ++PopEpoch;
1340 }
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001341
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001342 for (MemoryAccess &MA : *Accesses) {
1343 auto *MU = dyn_cast<MemoryUse>(&MA);
1344 if (!MU) {
1345 VersionStack.push_back(&MA);
1346 ++StackEpoch;
1347 continue;
1348 }
1349
George Burgess IV024f3d22016-08-03 19:57:02 +00001350 if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001351 MU->setDefiningAccess(MSSA->getLiveOnEntryDef(), true, None);
George Burgess IV024f3d22016-08-03 19:57:02 +00001352 continue;
1353 }
1354
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001355 MemoryLocOrCall UseMLOC(MU);
1356 auto &LocInfo = LocStackInfo[UseMLOC];
Daniel Berlin26fcea92016-08-02 20:02:21 +00001357 // If the pop epoch changed, it means we've removed stuff from top of
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001358 // stack due to changing blocks. We may have to reset the lower bound or
1359 // last kill info.
1360 if (LocInfo.PopEpoch != PopEpoch) {
1361 LocInfo.PopEpoch = PopEpoch;
1362 LocInfo.StackEpoch = StackEpoch;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001363 // If the lower bound was in something that no longer dominates us, we
1364 // have to reset it.
1365 // We can't simply track stack size, because the stack may have had
1366 // pushes/pops in the meantime.
1367 // XXX: This is non-optimal, but only is slower cases with heavily
1368 // branching dominator trees. To get the optimal number of queries would
1369 // be to make lowerbound and lastkill a per-loc stack, and pop it until
1370 // the top of that stack dominates us. This does not seem worth it ATM.
1371 // A much cheaper optimization would be to always explore the deepest
1372 // branch of the dominator tree first. This will guarantee this resets on
1373 // the smallest set of blocks.
1374 if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
Daniel Berlin1e98c042016-09-26 17:22:54 +00001375 !DT->dominates(LocInfo.LowerBoundBlock, BB)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001376 // Reset the lower bound of things to check.
1377 // TODO: Some day we should be able to reset to last kill, rather than
1378 // 0.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001379 LocInfo.LowerBound = 0;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001380 LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001381 LocInfo.LastKillValid = false;
1382 }
1383 } else if (LocInfo.StackEpoch != StackEpoch) {
1384 // If all that has changed is the StackEpoch, we only have to check the
1385 // new things on the stack, because we've checked everything before. In
1386 // this case, the lower bound of things to check remains the same.
1387 LocInfo.PopEpoch = PopEpoch;
1388 LocInfo.StackEpoch = StackEpoch;
1389 }
1390 if (!LocInfo.LastKillValid) {
1391 LocInfo.LastKill = VersionStack.size() - 1;
1392 LocInfo.LastKillValid = true;
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001393 LocInfo.AR = MayAlias;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001394 }
1395
1396 // At this point, we should have corrected last kill and LowerBound to be
1397 // in bounds.
1398 assert(LocInfo.LowerBound < VersionStack.size() &&
1399 "Lower bound out of range");
1400 assert(LocInfo.LastKill < VersionStack.size() &&
1401 "Last kill info out of range");
1402 // In any case, the new upper bound is the top of the stack.
1403 unsigned long UpperBound = VersionStack.size() - 1;
1404
1405 if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001406 LLVM_DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
1407 << *(MU->getMemoryInst()) << ")"
1408 << " because there are "
1409 << UpperBound - LocInfo.LowerBound
1410 << " stores to disambiguate\n");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001411 // Because we did not walk, LastKill is no longer valid, as this may
1412 // have been a kill.
1413 LocInfo.LastKillValid = false;
1414 continue;
1415 }
1416 bool FoundClobberResult = false;
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001417 unsigned UpwardWalkLimit = MaxCheckLimit;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001418 while (UpperBound > LocInfo.LowerBound) {
1419 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1420 // For phis, use the walker, see where we ended up, go there
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001421 MemoryAccess *Result =
1422 Walker->getClobberingMemoryAccess(MU, UpwardWalkLimit);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001423 // We are guaranteed to find it or something is wrong
1424 while (VersionStack[UpperBound] != Result) {
1425 assert(UpperBound != 0);
1426 --UpperBound;
1427 }
1428 FoundClobberResult = true;
1429 break;
1430 }
1431
1432 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
Daniel Berlindf101192016-08-03 00:01:46 +00001433 // If the lifetime of the pointer ends at this instruction, it's live on
1434 // entry.
1435 if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1436 // Reset UpperBound to liveOnEntryDef's place in the stack
1437 UpperBound = 0;
1438 FoundClobberResult = true;
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001439 LocInfo.AR = MustAlias;
Daniel Berlindf101192016-08-03 00:01:46 +00001440 break;
1441 }
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001442 ClobberAlias CA = instructionClobbersQuery(MD, MU, UseMLOC, *AA);
1443 if (CA.IsClobber) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001444 FoundClobberResult = true;
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001445 LocInfo.AR = CA.AR;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001446 break;
1447 }
1448 --UpperBound;
1449 }
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001450
1451 // Note: Phis always have AliasResult AR set to MayAlias ATM.
1452
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001453 // At the end of this loop, UpperBound is either a clobber, or lower bound
1454 // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1455 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001456 // We were last killed now by where we got to
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001457 if (MSSA->isLiveOnEntryDef(VersionStack[UpperBound]))
1458 LocInfo.AR = None;
1459 MU->setDefiningAccess(VersionStack[UpperBound], true, LocInfo.AR);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001460 LocInfo.LastKill = UpperBound;
1461 } else {
1462 // Otherwise, we checked all the new ones, and now we know we can get to
1463 // LastKill.
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001464 MU->setDefiningAccess(VersionStack[LocInfo.LastKill], true, LocInfo.AR);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001465 }
1466 LocInfo.LowerBound = VersionStack.size() - 1;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001467 LocInfo.LowerBoundBlock = BB;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001468 }
1469}
1470
1471/// Optimize uses to point to their actual clobbering definitions.
1472void MemorySSA::OptimizeUses::optimizeUses() {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001473 SmallVector<MemoryAccess *, 16> VersionStack;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001474 DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001475 VersionStack.push_back(MSSA->getLiveOnEntryDef());
1476
1477 unsigned long StackEpoch = 1;
1478 unsigned long PopEpoch = 1;
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001479 // We perform a non-recursive top-down dominator tree walk.
Daniel Berlin7ac3d742016-08-05 22:09:14 +00001480 for (const auto *DomNode : depth_first(DT->getRootNode()))
1481 optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1482 LocStackInfo);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001483}
1484
Daniel Berlin3d512a22016-08-22 19:14:30 +00001485void MemorySSA::placePHINodes(
Michael Zolotukhin67cfbaa2018-05-15 18:40:29 +00001486 const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks) {
Daniel Berlin3d512a22016-08-22 19:14:30 +00001487 // Determine where our MemoryPhi's should go
1488 ForwardIDFCalculator IDFs(*DT);
1489 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001490 SmallVector<BasicBlock *, 32> IDFBlocks;
1491 IDFs.calculate(IDFBlocks);
1492
1493 // Now place MemoryPhi nodes.
Daniel Berlind602e042017-01-25 20:56:19 +00001494 for (auto &BB : IDFBlocks)
1495 createMemoryPhi(BB);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001496}
1497
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001498void MemorySSA::buildMemorySSA(BatchAAResults &BAA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001499 // We create an access to represent "live on entry", for things like
1500 // arguments or users of globals, where the memory they use is defined before
1501 // the beginning of the function. We do not actually insert it into the IR.
1502 // We do not define a live on exit for the immediate uses, and thus our
1503 // semantics do *not* imply that something with no immediate uses can simply
1504 // be removed.
1505 BasicBlock &StartingPoint = F.getEntryBlock();
George Burgess IV612cf212018-02-27 06:43:19 +00001506 LiveOnEntryDef.reset(new MemoryDef(F.getContext(), nullptr, nullptr,
1507 &StartingPoint, NextID++));
George Burgess IVe1100f52016-02-02 22:46:49 +00001508
1509 // We maintain lists of memory accesses per-block, trading memory for time. We
1510 // could just look up the memory access for every possible instruction in the
1511 // stream.
1512 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001513 // Go through each block, figure out where defs occur, and chain together all
1514 // the accesses.
1515 for (BasicBlock &B : F) {
Daniel Berlin7898ca62016-02-07 01:52:15 +00001516 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001517 AccessList *Accesses = nullptr;
Daniel Berlind602e042017-01-25 20:56:19 +00001518 DefsList *Defs = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001519 for (Instruction &I : B) {
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001520 MemoryUseOrDef *MUD = createNewAccess(&I, &BAA);
George Burgess IVb42b7622016-03-11 19:34:03 +00001521 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001522 continue;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001523
George Burgess IVe1100f52016-02-02 22:46:49 +00001524 if (!Accesses)
1525 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001526 Accesses->push_back(MUD);
Daniel Berlind602e042017-01-25 20:56:19 +00001527 if (isa<MemoryDef>(MUD)) {
1528 InsertIntoDef = true;
1529 if (!Defs)
1530 Defs = getOrCreateDefsList(&B);
1531 Defs->push_back(*MUD);
1532 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001533 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001534 if (InsertIntoDef)
1535 DefiningBlocks.insert(&B);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001536 }
Michael Zolotukhin67cfbaa2018-05-15 18:40:29 +00001537 placePHINodes(DefiningBlocks);
George Burgess IVe1100f52016-02-02 22:46:49 +00001538
1539 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1540 // filled in with all blocks.
1541 SmallPtrSet<BasicBlock *, 16> Visited;
1542 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1543
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001544 ClobberWalkerBase<BatchAAResults> WalkerBase(this, &BAA, DT);
1545 CachingWalker<BatchAAResults> WalkerLocal(this, &WalkerBase);
1546 OptimizeUses(this, &WalkerLocal, &BAA, DT).optimizeUses();
George Burgess IV5f308972016-07-19 01:29:15 +00001547
George Burgess IVe1100f52016-02-02 22:46:49 +00001548 // Mark the uses in unreachable blocks as live on entry, so that they go
1549 // somewhere.
1550 for (auto &BB : F)
1551 if (!Visited.count(&BB))
1552 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001553}
George Burgess IVe1100f52016-02-02 22:46:49 +00001554
George Burgess IV5f308972016-07-19 01:29:15 +00001555MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1556
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001557MemorySSA::CachingWalker<AliasAnalysis> *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001558 if (Walker)
1559 return Walker.get();
1560
Alina Sbirleabc8aa242019-01-07 19:22:37 +00001561 if (!WalkerBase)
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001562 WalkerBase =
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001563 std::make_unique<ClobberWalkerBase<AliasAnalysis>>(this, AA, DT);
Alina Sbirleabc8aa242019-01-07 19:22:37 +00001564
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001565 Walker =
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001566 std::make_unique<CachingWalker<AliasAnalysis>>(this, WalkerBase.get());
Geoff Berryb96d3b22016-06-01 21:30:40 +00001567 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001568}
1569
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001570MemorySSAWalker *MemorySSA::getSkipSelfWalker() {
1571 if (SkipWalker)
1572 return SkipWalker.get();
1573
1574 if (!WalkerBase)
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001575 WalkerBase =
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001576 std::make_unique<ClobberWalkerBase<AliasAnalysis>>(this, AA, DT);
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001577
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001578 SkipWalker =
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001579 std::make_unique<SkipSelfWalker<AliasAnalysis>>(this, WalkerBase.get());
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001580 return SkipWalker.get();
1581 }
1582
1583
Daniel Berlind602e042017-01-25 20:56:19 +00001584// This is a helper function used by the creation routines. It places NewAccess
1585// into the access and defs lists for a given basic block, at the given
1586// insertion point.
1587void MemorySSA::insertIntoListsForBlock(MemoryAccess *NewAccess,
1588 const BasicBlock *BB,
1589 InsertionPlace Point) {
1590 auto *Accesses = getOrCreateAccessList(BB);
1591 if (Point == Beginning) {
1592 // If it's a phi node, it goes first, otherwise, it goes after any phi
1593 // nodes.
1594 if (isa<MemoryPhi>(NewAccess)) {
1595 Accesses->push_front(NewAccess);
1596 auto *Defs = getOrCreateDefsList(BB);
1597 Defs->push_front(*NewAccess);
1598 } else {
1599 auto AI = find_if_not(
1600 *Accesses, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1601 Accesses->insert(AI, NewAccess);
1602 if (!isa<MemoryUse>(NewAccess)) {
1603 auto *Defs = getOrCreateDefsList(BB);
1604 auto DI = find_if_not(
1605 *Defs, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1606 Defs->insert(DI, *NewAccess);
1607 }
1608 }
1609 } else {
1610 Accesses->push_back(NewAccess);
1611 if (!isa<MemoryUse>(NewAccess)) {
1612 auto *Defs = getOrCreateDefsList(BB);
1613 Defs->push_back(*NewAccess);
1614 }
1615 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001616 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001617}
1618
1619void MemorySSA::insertIntoListsBefore(MemoryAccess *What, const BasicBlock *BB,
1620 AccessList::iterator InsertPt) {
1621 auto *Accesses = getWritableBlockAccesses(BB);
1622 bool WasEnd = InsertPt == Accesses->end();
1623 Accesses->insert(AccessList::iterator(InsertPt), What);
1624 if (!isa<MemoryUse>(What)) {
1625 auto *Defs = getOrCreateDefsList(BB);
1626 // If we got asked to insert at the end, we have an easy job, just shove it
1627 // at the end. If we got asked to insert before an existing def, we also get
Zhaoshi Zhenga5531f22018-04-04 21:08:11 +00001628 // an iterator. If we got asked to insert before a use, we have to hunt for
Daniel Berlind602e042017-01-25 20:56:19 +00001629 // the next def.
1630 if (WasEnd) {
1631 Defs->push_back(*What);
1632 } else if (isa<MemoryDef>(InsertPt)) {
1633 Defs->insert(InsertPt->getDefsIterator(), *What);
1634 } else {
1635 while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt))
1636 ++InsertPt;
1637 // Either we found a def, or we are inserting at the end
1638 if (InsertPt == Accesses->end())
1639 Defs->push_back(*What);
1640 else
1641 Defs->insert(InsertPt->getDefsIterator(), *What);
1642 }
1643 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001644 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001645}
1646
George Burgess IV5676a5d2018-08-22 22:34:38 +00001647void MemorySSA::prepareForMoveTo(MemoryAccess *What, BasicBlock *BB) {
1648 // Keep it in the lookup tables, remove from the lists
1649 removeFromLists(What, false);
1650
1651 // Note that moving should implicitly invalidate the optimized state of a
1652 // MemoryUse (and Phis can't be optimized). However, it doesn't do so for a
1653 // MemoryDef.
1654 if (auto *MD = dyn_cast<MemoryDef>(What))
1655 MD->resetOptimized();
1656 What->setBlock(BB);
1657}
1658
Zhaoshi Zhenga5531f22018-04-04 21:08:11 +00001659// Move What before Where in the IR. The end result is that What will belong to
Daniel Berlin60ead052017-01-28 01:23:13 +00001660// the right lists and have the right Block set, but will not otherwise be
1661// correct. It will not have the right defining access, and if it is a def,
1662// things below it will not properly be updated.
1663void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
1664 AccessList::iterator Where) {
George Burgess IV5676a5d2018-08-22 22:34:38 +00001665 prepareForMoveTo(What, BB);
Daniel Berlin60ead052017-01-28 01:23:13 +00001666 insertIntoListsBefore(What, BB, Where);
1667}
1668
Alina Sbirlea0f533552018-07-11 22:11:46 +00001669void MemorySSA::moveTo(MemoryAccess *What, BasicBlock *BB,
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001670 InsertionPlace Point) {
Alina Sbirlea0f533552018-07-11 22:11:46 +00001671 if (isa<MemoryPhi>(What)) {
1672 assert(Point == Beginning &&
1673 "Can only move a Phi at the beginning of the block");
1674 // Update lookup table entry
1675 ValueToMemoryAccess.erase(What->getBlock());
1676 bool Inserted = ValueToMemoryAccess.insert({BB, What}).second;
1677 (void)Inserted;
1678 assert(Inserted && "Cannot move a Phi to a block that already has one");
1679 }
1680
George Burgess IV5676a5d2018-08-22 22:34:38 +00001681 prepareForMoveTo(What, BB);
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001682 insertIntoListsForBlock(What, BB, Point);
1683}
1684
Daniel Berlin14300262016-06-21 18:39:20 +00001685MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1686 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
Daniel Berlin14300262016-06-21 18:39:20 +00001687 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001688 // Phi's always are placed at the front of the block.
Daniel Berlind602e042017-01-25 20:56:19 +00001689 insertIntoListsForBlock(Phi, BB, Beginning);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001690 ValueToMemoryAccess[BB] = Phi;
Daniel Berlin14300262016-06-21 18:39:20 +00001691 return Phi;
1692}
1693
1694MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
Alina Sbirlea79800992018-09-10 20:13:01 +00001695 MemoryAccess *Definition,
Alina Sbirlea4bc625c2019-07-30 20:10:33 +00001696 const MemoryUseOrDef *Template,
1697 bool CreationMustSucceed) {
Daniel Berlin14300262016-06-21 18:39:20 +00001698 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001699 MemoryUseOrDef *NewAccess = createNewAccess(I, AA, Template);
Alina Sbirlea4bc625c2019-07-30 20:10:33 +00001700 if (CreationMustSucceed)
1701 assert(NewAccess != nullptr && "Tried to create a memory access for a "
1702 "non-memory touching instruction");
1703 if (NewAccess)
1704 NewAccess->setDefiningAccess(Definition);
Daniel Berlin14300262016-06-21 18:39:20 +00001705 return NewAccess;
1706}
1707
Daniel Berlind952cea2017-04-07 01:28:36 +00001708// Return true if the instruction has ordering constraints.
1709// Note specifically that this only considers stores and loads
1710// because others are still considered ModRef by getModRefInfo.
1711static inline bool isOrdered(const Instruction *I) {
1712 if (auto *SI = dyn_cast<StoreInst>(I)) {
1713 if (!SI->isUnordered())
1714 return true;
1715 } else if (auto *LI = dyn_cast<LoadInst>(I)) {
1716 if (!LI->isUnordered())
1717 return true;
1718 }
1719 return false;
1720}
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001721
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001722/// Helper function to create new memory accesses
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001723template <typename AliasAnalysisType>
Alina Sbirlea79800992018-09-10 20:13:01 +00001724MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I,
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001725 AliasAnalysisType *AAP,
Alina Sbirlea79800992018-09-10 20:13:01 +00001726 const MemoryUseOrDef *Template) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001727 // The assume intrinsic has a control dependency which we model by claiming
1728 // that it writes arbitrarily. Ignore that fake memory dependency here.
1729 // FIXME: Replace this special casing with a more accurate modelling of
1730 // assume's control dependency.
1731 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1732 if (II->getIntrinsicID() == Intrinsic::assume)
1733 return nullptr;
1734
Alina Sbirlea79800992018-09-10 20:13:01 +00001735 bool Def, Use;
1736 if (Template) {
1737 Def = dyn_cast_or_null<MemoryDef>(Template) != nullptr;
1738 Use = dyn_cast_or_null<MemoryUse>(Template) != nullptr;
1739#if !defined(NDEBUG)
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001740 ModRefInfo ModRef = AAP->getModRefInfo(I, None);
Alina Sbirlea79800992018-09-10 20:13:01 +00001741 bool DefCheck, UseCheck;
1742 DefCheck = isModSet(ModRef) || isOrdered(I);
1743 UseCheck = isRefSet(ModRef);
1744 assert(Def == DefCheck && (Def || Use == UseCheck) && "Invalid template");
1745#endif
1746 } else {
1747 // Find out what affect this instruction has on memory.
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001748 ModRefInfo ModRef = AAP->getModRefInfo(I, None);
Alina Sbirlea79800992018-09-10 20:13:01 +00001749 // The isOrdered check is used to ensure that volatiles end up as defs
1750 // (atomics end up as ModRef right now anyway). Until we separate the
1751 // ordering chain from the memory chain, this enables people to see at least
1752 // some relative ordering to volatiles. Note that getClobberingMemoryAccess
1753 // will still give an answer that bypasses other volatile loads. TODO:
1754 // Separate memory aliasing and ordering into two different chains so that
1755 // we can precisely represent both "what memory will this read/write/is
1756 // clobbered by" and "what instructions can I move this past".
1757 Def = isModSet(ModRef) || isOrdered(I);
1758 Use = isRefSet(ModRef);
1759 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001760
1761 // It's possible for an instruction to not modify memory at all. During
1762 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +00001763 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +00001764 return nullptr;
1765
George Burgess IVb42b7622016-03-11 19:34:03 +00001766 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001767 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +00001768 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +00001769 else
George Burgess IVb42b7622016-03-11 19:34:03 +00001770 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
Daniel Berlin5130cc82016-07-31 21:08:20 +00001771 ValueToMemoryAccess[I] = MUD;
George Burgess IVb42b7622016-03-11 19:34:03 +00001772 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001773}
1774
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001775/// Returns true if \p Replacer dominates \p Replacee .
George Burgess IVe1100f52016-02-02 22:46:49 +00001776bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1777 const MemoryAccess *Replacee) const {
1778 if (isa<MemoryUseOrDef>(Replacee))
1779 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1780 const auto *MP = cast<MemoryPhi>(Replacee);
1781 // For a phi node, the use occurs in the predecessor block of the phi node.
1782 // Since we may occur multiple times in the phi node, we have to check each
1783 // operand to ensure Replacer dominates each operand where Replacee occurs.
1784 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +00001785 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +00001786 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1787 return false;
1788 }
1789 return true;
1790}
1791
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001792/// Properly remove \p MA from all of MemorySSA's lookup tables.
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001793void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1794 assert(MA->use_empty() &&
1795 "Trying to remove memory access that still has uses");
Daniel Berlin5c46b942016-07-19 22:49:43 +00001796 BlockNumbering.erase(MA);
George Burgess IV2cbf9732018-06-22 22:34:07 +00001797 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001798 MUD->setDefiningAccess(nullptr);
1799 // Invalidate our walker's cache if necessary
1800 if (!isa<MemoryUse>(MA))
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001801 getWalker()->invalidateInfo(MA);
George Burgess IV2cbf9732018-06-22 22:34:07 +00001802
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001803 Value *MemoryInst;
George Burgess IV2cbf9732018-06-22 22:34:07 +00001804 if (const auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001805 MemoryInst = MUD->getMemoryInst();
George Burgess IV2cbf9732018-06-22 22:34:07 +00001806 else
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001807 MemoryInst = MA->getBlock();
George Burgess IV2cbf9732018-06-22 22:34:07 +00001808
Daniel Berlin5130cc82016-07-31 21:08:20 +00001809 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1810 if (VMA->second == MA)
1811 ValueToMemoryAccess.erase(VMA);
Daniel Berlin60ead052017-01-28 01:23:13 +00001812}
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001813
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001814/// Properly remove \p MA from all of MemorySSA's lists.
Daniel Berlin60ead052017-01-28 01:23:13 +00001815///
1816/// Because of the way the intrusive list and use lists work, it is important to
1817/// do removal in the right order.
1818/// ShouldDelete defaults to true, and will cause the memory access to also be
1819/// deleted, not just removed.
1820void MemorySSA::removeFromLists(MemoryAccess *MA, bool ShouldDelete) {
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001821 BasicBlock *BB = MA->getBlock();
Daniel Berlind602e042017-01-25 20:56:19 +00001822 // The access list owns the reference, so we erase it from the non-owning list
1823 // first.
1824 if (!isa<MemoryUse>(MA)) {
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001825 auto DefsIt = PerBlockDefs.find(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001826 std::unique_ptr<DefsList> &Defs = DefsIt->second;
1827 Defs->remove(*MA);
1828 if (Defs->empty())
1829 PerBlockDefs.erase(DefsIt);
1830 }
1831
Daniel Berlin60ead052017-01-28 01:23:13 +00001832 // The erase call here will delete it. If we don't want it deleted, we call
1833 // remove instead.
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001834 auto AccessIt = PerBlockAccesses.find(BB);
Daniel Berlinada263d2016-06-20 20:21:33 +00001835 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin60ead052017-01-28 01:23:13 +00001836 if (ShouldDelete)
1837 Accesses->erase(MA);
1838 else
1839 Accesses->remove(MA);
1840
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001841 if (Accesses->empty()) {
George Burgess IVe0e6e482016-03-02 02:35:04 +00001842 PerBlockAccesses.erase(AccessIt);
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001843 BlockNumberingValid.erase(BB);
1844 }
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001845}
1846
George Burgess IVe1100f52016-02-02 22:46:49 +00001847void MemorySSA::print(raw_ostream &OS) const {
1848 MemorySSAAnnotatedWriter Writer(this);
1849 F.print(OS, &Writer);
1850}
1851
Aaron Ballman615eb472017-10-15 14:32:27 +00001852#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Daniel Berlin78cbd282017-02-20 22:26:03 +00001853LLVM_DUMP_METHOD void MemorySSA::dump() const { print(dbgs()); }
Matthias Braun8c209aa2017-01-28 02:02:38 +00001854#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001855
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001856void MemorySSA::verifyMemorySSA() const {
1857 verifyDefUses(F);
1858 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001859 verifyOrdering(F);
George Burgess IV97ec6242018-06-25 05:30:36 +00001860 verifyDominationNumbers(F);
Alina Sbirlea63e97fa2019-07-31 17:41:04 +00001861 verifyPrevDefInPhis(F);
Alina Sbirlead77edc02019-02-11 19:51:21 +00001862 // Previously, the verification used to also verify that the clobberingAccess
1863 // cached by MemorySSA is the same as the clobberingAccess found at a later
1864 // query to AA. This does not hold true in general due to the current fragility
1865 // of BasicAA which has arbitrary caps on the things it analyzes before giving
1866 // up. As a result, transformations that are correct, will lead to BasicAA
1867 // returning different Alias answers before and after that transformation.
1868 // Invalidating MemorySSA is not an option, as the results in BasicAA can be so
1869 // random, in the worst case we'd need to rebuild MemorySSA from scratch after
1870 // every transformation, which defeats the purpose of using it. For such an
1871 // example, see test4 added in D51960.
Daniel Berlin14300262016-06-21 18:39:20 +00001872}
1873
Alina Sbirlea63e97fa2019-07-31 17:41:04 +00001874void MemorySSA::verifyPrevDefInPhis(Function &F) const {
Alina Sbirlea594f0e02019-09-04 00:44:54 +00001875#if !defined(NDEBUG) && defined(EXPENSIVE_CHECKS)
Alina Sbirlea63e97fa2019-07-31 17:41:04 +00001876 for (const BasicBlock &BB : F) {
1877 if (MemoryPhi *Phi = getMemoryAccess(&BB)) {
1878 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
1879 auto *Pred = Phi->getIncomingBlock(I);
1880 auto *IncAcc = Phi->getIncomingValue(I);
1881 // If Pred has no unreachable predecessors, get last def looking at
1882 // IDoms. If, while walkings IDoms, any of these has an unreachable
Alina Sbirlea1a3fdaf2019-08-19 18:57:40 +00001883 // predecessor, then the incoming def can be any access.
Alina Sbirlea63e97fa2019-07-31 17:41:04 +00001884 if (auto *DTNode = DT->getNode(Pred)) {
1885 while (DTNode) {
1886 if (auto *DefList = getBlockDefs(DTNode->getBlock())) {
1887 auto *LastAcc = &*(--DefList->end());
1888 assert(LastAcc == IncAcc &&
1889 "Incorrect incoming access into phi.");
1890 break;
1891 }
1892 DTNode = DTNode->getIDom();
1893 }
Alina Sbirlea1a3fdaf2019-08-19 18:57:40 +00001894 } else {
Alina Sbirlea63e97fa2019-07-31 17:41:04 +00001895 // If Pred has unreachable predecessors, but has at least a Def, the
1896 // incoming access can be the last Def in Pred, or it could have been
Alina Sbirlea1a3fdaf2019-08-19 18:57:40 +00001897 // optimized to LoE. After an update, though, the LoE may have been
1898 // replaced by another access, so IncAcc may be any access.
Alina Sbirlea63e97fa2019-07-31 17:41:04 +00001899 // If Pred has unreachable predecessors and no Defs, incoming access
Alina Sbirlea1a3fdaf2019-08-19 18:57:40 +00001900 // should be LoE; However, after an update, it may be any access.
Alina Sbirlea63e97fa2019-07-31 17:41:04 +00001901 }
1902 }
1903 }
1904 }
1905#endif
1906}
1907
George Burgess IV97ec6242018-06-25 05:30:36 +00001908/// Verify that all of the blocks we believe to have valid domination numbers
1909/// actually have valid domination numbers.
1910void MemorySSA::verifyDominationNumbers(const Function &F) const {
1911#ifndef NDEBUG
1912 if (BlockNumberingValid.empty())
1913 return;
1914
1915 SmallPtrSet<const BasicBlock *, 16> ValidBlocks = BlockNumberingValid;
1916 for (const BasicBlock &BB : F) {
1917 if (!ValidBlocks.count(&BB))
1918 continue;
1919
1920 ValidBlocks.erase(&BB);
1921
1922 const AccessList *Accesses = getBlockAccesses(&BB);
1923 // It's correct to say an empty block has valid numbering.
1924 if (!Accesses)
1925 continue;
1926
1927 // Block numbering starts at 1.
1928 unsigned long LastNumber = 0;
1929 for (const MemoryAccess &MA : *Accesses) {
1930 auto ThisNumberIter = BlockNumbering.find(&MA);
1931 assert(ThisNumberIter != BlockNumbering.end() &&
1932 "MemoryAccess has no domination number in a valid block!");
1933
1934 unsigned long ThisNumber = ThisNumberIter->second;
1935 assert(ThisNumber > LastNumber &&
1936 "Domination numbers should be strictly increasing!");
1937 LastNumber = ThisNumber;
1938 }
1939 }
1940
1941 assert(ValidBlocks.empty() &&
1942 "All valid BasicBlocks should exist in F -- dangling pointers?");
1943#endif
1944}
1945
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001946/// Verify that the order and existence of MemoryAccesses matches the
Daniel Berlin14300262016-06-21 18:39:20 +00001947/// order and existence of memory affecting instructions.
1948void MemorySSA::verifyOrdering(Function &F) const {
George Burgess IV6a9aa022018-08-28 00:32:32 +00001949#ifndef NDEBUG
Daniel Berlin14300262016-06-21 18:39:20 +00001950 // Walk all the blocks, comparing what the lookups think and what the access
1951 // lists think, as well as the order in the blocks vs the order in the access
1952 // lists.
1953 SmallVector<MemoryAccess *, 32> ActualAccesses;
Daniel Berlind602e042017-01-25 20:56:19 +00001954 SmallVector<MemoryAccess *, 32> ActualDefs;
Daniel Berlin14300262016-06-21 18:39:20 +00001955 for (BasicBlock &B : F) {
1956 const AccessList *AL = getBlockAccesses(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001957 const auto *DL = getBlockDefs(&B);
Daniel Berlin14300262016-06-21 18:39:20 +00001958 MemoryAccess *Phi = getMemoryAccess(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001959 if (Phi) {
Daniel Berlin14300262016-06-21 18:39:20 +00001960 ActualAccesses.push_back(Phi);
Daniel Berlind602e042017-01-25 20:56:19 +00001961 ActualDefs.push_back(Phi);
1962 }
1963
Daniel Berlin14300262016-06-21 18:39:20 +00001964 for (Instruction &I : B) {
1965 MemoryAccess *MA = getMemoryAccess(&I);
Daniel Berlind602e042017-01-25 20:56:19 +00001966 assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) &&
1967 "We have memory affecting instructions "
1968 "in this block but they are not in the "
1969 "access list or defs list");
1970 if (MA) {
Daniel Berlin14300262016-06-21 18:39:20 +00001971 ActualAccesses.push_back(MA);
Daniel Berlind602e042017-01-25 20:56:19 +00001972 if (isa<MemoryDef>(MA))
1973 ActualDefs.push_back(MA);
1974 }
Daniel Berlin14300262016-06-21 18:39:20 +00001975 }
1976 // Either we hit the assert, really have no accesses, or we have both
Daniel Berlind602e042017-01-25 20:56:19 +00001977 // accesses and an access list.
1978 // Same with defs.
1979 if (!AL && !DL)
Daniel Berlin14300262016-06-21 18:39:20 +00001980 continue;
1981 assert(AL->size() == ActualAccesses.size() &&
1982 "We don't have the same number of accesses in the block as on the "
1983 "access list");
Davide Italiano6c77de02017-01-30 03:16:43 +00001984 assert((DL || ActualDefs.size() == 0) &&
1985 "Either we should have a defs list, or we should have no defs");
Daniel Berlind602e042017-01-25 20:56:19 +00001986 assert((!DL || DL->size() == ActualDefs.size()) &&
1987 "We don't have the same number of defs in the block as on the "
1988 "def list");
Daniel Berlin14300262016-06-21 18:39:20 +00001989 auto ALI = AL->begin();
1990 auto AAI = ActualAccesses.begin();
1991 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1992 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1993 ++ALI;
1994 ++AAI;
1995 }
1996 ActualAccesses.clear();
Daniel Berlind602e042017-01-25 20:56:19 +00001997 if (DL) {
1998 auto DLI = DL->begin();
1999 auto ADI = ActualDefs.begin();
2000 while (DLI != DL->end() && ADI != ActualDefs.end()) {
2001 assert(&*DLI == *ADI && "Not the same defs in the same order");
2002 ++DLI;
2003 ++ADI;
2004 }
2005 }
2006 ActualDefs.clear();
Daniel Berlin14300262016-06-21 18:39:20 +00002007 }
George Burgess IV6a9aa022018-08-28 00:32:32 +00002008#endif
Daniel Berlin932b4cb2016-02-10 17:39:43 +00002009}
2010
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002011/// Verify the domination properties of MemorySSA by checking that each
George Burgess IVe1100f52016-02-02 22:46:49 +00002012/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00002013void MemorySSA::verifyDomination(Function &F) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00002014#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00002015 for (BasicBlock &B : F) {
2016 // Phi nodes are attached to basic blocks
Daniel Berlin2919b1c2016-08-05 21:46:52 +00002017 if (MemoryPhi *MP = getMemoryAccess(&B))
2018 for (const Use &U : MP->uses())
2019 assert(dominates(MP, U) && "Memory PHI does not dominate it's uses");
Daniel Berlin7af95872016-08-05 21:47:20 +00002020
George Burgess IVe1100f52016-02-02 22:46:49 +00002021 for (Instruction &I : B) {
2022 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
2023 if (!MD)
2024 continue;
2025
Daniel Berlin2919b1c2016-08-05 21:46:52 +00002026 for (const Use &U : MD->uses())
2027 assert(dominates(MD, U) && "Memory Def does not dominate it's uses");
George Burgess IVe1100f52016-02-02 22:46:49 +00002028 }
2029 }
Daniel Berlin7af95872016-08-05 21:47:20 +00002030#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00002031}
2032
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002033/// Verify the def-use lists in MemorySSA, by verifying that \p Use
George Burgess IVe1100f52016-02-02 22:46:49 +00002034/// appears in the use list of \p Def.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00002035void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00002036#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00002037 // The live on entry use may cause us to get a NULL def here
Daniel Berlin7af95872016-08-05 21:47:20 +00002038 if (!Def)
2039 assert(isLiveOnEntryDef(Use) &&
2040 "Null def but use not point to live on entry def");
2041 else
Daniel Berlinda2f38e2016-08-11 21:26:50 +00002042 assert(is_contained(Def->users(), Use) &&
Daniel Berlin7af95872016-08-05 21:47:20 +00002043 "Did not find use in def's use list");
2044#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00002045}
2046
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002047/// Verify the immediate use information, by walking all the memory
George Burgess IVe1100f52016-02-02 22:46:49 +00002048/// accesses and verifying that, for each use, it appears in the
2049/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00002050void MemorySSA::verifyDefUses(Function &F) const {
Alina Sbirlea594f0e02019-09-04 00:44:54 +00002051#if !defined(NDEBUG) && defined(EXPENSIVE_CHECKS)
George Burgess IVe1100f52016-02-02 22:46:49 +00002052 for (BasicBlock &B : F) {
2053 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00002054 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00002055 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
2056 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00002057 "Incomplete MemoryPhi Node");
Alina Sbirlea201d02c2018-06-20 21:06:13 +00002058 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002059 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Alina Sbirlea201d02c2018-06-20 21:06:13 +00002060 assert(find(predecessors(&B), Phi->getIncomingBlock(I)) !=
2061 pred_end(&B) &&
2062 "Incoming phi block not a block predecessor");
2063 }
Daniel Berlin14300262016-06-21 18:39:20 +00002064 }
George Burgess IVe1100f52016-02-02 22:46:49 +00002065
2066 for (Instruction &I : B) {
George Burgess IV66837ab2016-11-01 21:17:46 +00002067 if (MemoryUseOrDef *MA = getMemoryAccess(&I)) {
2068 verifyUseInDefs(MA->getDefiningAccess(), MA);
George Burgess IVe1100f52016-02-02 22:46:49 +00002069 }
2070 }
2071 }
George Burgess IV6a9aa022018-08-28 00:32:32 +00002072#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00002073}
2074
Daniel Berlin5c46b942016-07-19 22:49:43 +00002075/// Perform a local numbering on blocks so that instruction ordering can be
2076/// determined in constant time.
2077/// TODO: We currently just number in order. If we numbered by N, we could
2078/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
2079/// log2(N) sequences of mixed before and after) without needing to invalidate
2080/// the numbering.
2081void MemorySSA::renumberBlock(const BasicBlock *B) const {
2082 // The pre-increment ensures the numbers really start at 1.
2083 unsigned long CurrentNumber = 0;
2084 const AccessList *AL = getBlockAccesses(B);
2085 assert(AL != nullptr && "Asking to renumber an empty block");
2086 for (const auto &I : *AL)
2087 BlockNumbering[&I] = ++CurrentNumber;
2088 BlockNumberingValid.insert(B);
2089}
2090
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002091/// Determine, for two memory accesses in the same block,
George Burgess IVe1100f52016-02-02 22:46:49 +00002092/// whether \p Dominator dominates \p Dominatee.
2093/// \returns True if \p Dominator dominates \p Dominatee.
2094bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
2095 const MemoryAccess *Dominatee) const {
Daniel Berlin5c46b942016-07-19 22:49:43 +00002096 const BasicBlock *DominatorBlock = Dominator->getBlock();
Daniel Berlin5c46b942016-07-19 22:49:43 +00002097
Daniel Berlin19860302016-07-19 23:08:08 +00002098 assert((DominatorBlock == Dominatee->getBlock()) &&
Daniel Berlin5c46b942016-07-19 22:49:43 +00002099 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00002100 // A node dominates itself.
2101 if (Dominatee == Dominator)
2102 return true;
2103
2104 // When Dominatee is defined on function entry, it is not dominated by another
2105 // memory access.
2106 if (isLiveOnEntryDef(Dominatee))
2107 return false;
2108
2109 // When Dominator is defined on function entry, it dominates the other memory
2110 // access.
2111 if (isLiveOnEntryDef(Dominator))
2112 return true;
2113
Daniel Berlin5c46b942016-07-19 22:49:43 +00002114 if (!BlockNumberingValid.count(DominatorBlock))
2115 renumberBlock(DominatorBlock);
George Burgess IVe1100f52016-02-02 22:46:49 +00002116
Daniel Berlin5c46b942016-07-19 22:49:43 +00002117 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
2118 // All numbers start with 1
2119 assert(DominatorNum != 0 && "Block was not numbered properly");
2120 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
2121 assert(DominateeNum != 0 && "Block was not numbered properly");
2122 return DominatorNum < DominateeNum;
George Burgess IVe1100f52016-02-02 22:46:49 +00002123}
2124
George Burgess IV5f308972016-07-19 01:29:15 +00002125bool MemorySSA::dominates(const MemoryAccess *Dominator,
2126 const MemoryAccess *Dominatee) const {
2127 if (Dominator == Dominatee)
2128 return true;
2129
2130 if (isLiveOnEntryDef(Dominatee))
2131 return false;
2132
2133 if (Dominator->getBlock() != Dominatee->getBlock())
2134 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
2135 return locallyDominates(Dominator, Dominatee);
2136}
2137
Daniel Berlin2919b1c2016-08-05 21:46:52 +00002138bool MemorySSA::dominates(const MemoryAccess *Dominator,
2139 const Use &Dominatee) const {
2140 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
2141 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
2142 // The def must dominate the incoming block of the phi.
2143 if (UseBB != Dominator->getBlock())
2144 return DT->dominates(Dominator->getBlock(), UseBB);
2145 // If the UseBB and the DefBB are the same, compare locally.
2146 return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
2147 }
2148 // If it's not a PHI node use, the normal dominates can already handle it.
2149 return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
2150}
2151
George Burgess IVe1100f52016-02-02 22:46:49 +00002152const static char LiveOnEntryStr[] = "liveOnEntry";
2153
Reid Kleckner96ab8722017-05-18 17:24:10 +00002154void MemoryAccess::print(raw_ostream &OS) const {
2155 switch (getValueID()) {
2156 case MemoryPhiVal: return static_cast<const MemoryPhi *>(this)->print(OS);
2157 case MemoryDefVal: return static_cast<const MemoryDef *>(this)->print(OS);
2158 case MemoryUseVal: return static_cast<const MemoryUse *>(this)->print(OS);
2159 }
2160 llvm_unreachable("invalid value id");
2161}
2162
George Burgess IVe1100f52016-02-02 22:46:49 +00002163void MemoryDef::print(raw_ostream &OS) const {
2164 MemoryAccess *UO = getDefiningAccess();
2165
George Burgess IVaa283d82018-06-14 19:55:53 +00002166 auto printID = [&OS](MemoryAccess *A) {
2167 if (A && A->getID())
2168 OS << A->getID();
2169 else
2170 OS << LiveOnEntryStr;
2171 };
2172
George Burgess IVe1100f52016-02-02 22:46:49 +00002173 OS << getID() << " = MemoryDef(";
George Burgess IVaa283d82018-06-14 19:55:53 +00002174 printID(UO);
2175 OS << ")";
2176
2177 if (isOptimized()) {
2178 OS << "->";
2179 printID(getOptimized());
2180
2181 if (Optional<AliasResult> AR = getOptimizedAccessType())
2182 OS << " " << *AR;
2183 }
George Burgess IVe1100f52016-02-02 22:46:49 +00002184}
2185
2186void MemoryPhi::print(raw_ostream &OS) const {
2187 bool First = true;
2188 OS << getID() << " = MemoryPhi(";
2189 for (const auto &Op : operands()) {
2190 BasicBlock *BB = getIncomingBlock(Op);
2191 MemoryAccess *MA = cast<MemoryAccess>(Op);
2192 if (!First)
2193 OS << ',';
2194 else
2195 First = false;
2196
2197 OS << '{';
2198 if (BB->hasName())
2199 OS << BB->getName();
2200 else
2201 BB->printAsOperand(OS, false);
2202 OS << ',';
2203 if (unsigned ID = MA->getID())
2204 OS << ID;
2205 else
2206 OS << LiveOnEntryStr;
2207 OS << '}';
2208 }
2209 OS << ')';
2210}
2211
George Burgess IVe1100f52016-02-02 22:46:49 +00002212void MemoryUse::print(raw_ostream &OS) const {
2213 MemoryAccess *UO = getDefiningAccess();
2214 OS << "MemoryUse(";
2215 if (UO && UO->getID())
2216 OS << UO->getID();
2217 else
2218 OS << LiveOnEntryStr;
2219 OS << ')';
George Burgess IVaa283d82018-06-14 19:55:53 +00002220
2221 if (Optional<AliasResult> AR = getOptimizedAccessType())
2222 OS << " " << *AR;
George Burgess IVe1100f52016-02-02 22:46:49 +00002223}
2224
2225void MemoryAccess::dump() const {
Daniel Berlin78cbd282017-02-20 22:26:03 +00002226// Cannot completely remove virtual function even in release mode.
Aaron Ballman615eb472017-10-15 14:32:27 +00002227#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
George Burgess IVe1100f52016-02-02 22:46:49 +00002228 print(dbgs());
2229 dbgs() << "\n";
Matthias Braun8c209aa2017-01-28 02:02:38 +00002230#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00002231}
2232
Chad Rosier232e29e2016-07-06 21:20:47 +00002233char MemorySSAPrinterLegacyPass::ID = 0;
2234
2235MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
2236 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
2237}
2238
2239void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
2240 AU.setPreservesAll();
2241 AU.addRequired<MemorySSAWrapperPass>();
Chad Rosier232e29e2016-07-06 21:20:47 +00002242}
2243
2244bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
2245 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2246 MSSA.print(dbgs());
2247 if (VerifyMemorySSA)
2248 MSSA.verifyMemorySSA();
2249 return false;
2250}
2251
Chandler Carruthdab4eae2016-11-23 17:53:26 +00002252AnalysisKey MemorySSAAnalysis::Key;
George Burgess IVe1100f52016-02-02 22:46:49 +00002253
Daniel Berlin1e98c042016-09-26 17:22:54 +00002254MemorySSAAnalysis::Result MemorySSAAnalysis::run(Function &F,
2255 FunctionAnalysisManager &AM) {
Geoff Berryb96d3b22016-06-01 21:30:40 +00002256 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2257 auto &AA = AM.getResult<AAManager>(F);
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00002258 return MemorySSAAnalysis::Result(std::make_unique<MemorySSA>(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002259}
2260
Alina Sbirleab4683202019-04-30 22:43:55 +00002261bool MemorySSAAnalysis::Result::invalidate(
2262 Function &F, const PreservedAnalyses &PA,
2263 FunctionAnalysisManager::Invalidator &Inv) {
2264 auto PAC = PA.getChecker<MemorySSAAnalysis>();
2265 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
2266 Inv.invalidate<AAManager>(F, PA) ||
2267 Inv.invalidate<DominatorTreeAnalysis>(F, PA);
2268}
2269
Geoff Berryb96d3b22016-06-01 21:30:40 +00002270PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
2271 FunctionAnalysisManager &AM) {
2272 OS << "MemorySSA for function: " << F.getName() << "\n";
Geoff Berry290a13e2016-08-08 18:27:22 +00002273 AM.getResult<MemorySSAAnalysis>(F).getMSSA().print(OS);
Geoff Berryb96d3b22016-06-01 21:30:40 +00002274
2275 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00002276}
2277
Geoff Berryb96d3b22016-06-01 21:30:40 +00002278PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
2279 FunctionAnalysisManager &AM) {
Geoff Berry290a13e2016-08-08 18:27:22 +00002280 AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002281
2282 return PreservedAnalyses::all();
2283}
2284
2285char MemorySSAWrapperPass::ID = 0;
2286
2287MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
2288 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
2289}
2290
2291void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
2292
2293void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002294 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002295 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
2296 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00002297}
2298
Geoff Berryb96d3b22016-06-01 21:30:40 +00002299bool MemorySSAWrapperPass::runOnFunction(Function &F) {
2300 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2301 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2302 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002303 return false;
2304}
2305
Geoff Berryb96d3b22016-06-01 21:30:40 +00002306void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00002307
Geoff Berryb96d3b22016-06-01 21:30:40 +00002308void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002309 MSSA->print(OS);
2310}
2311
George Burgess IVe1100f52016-02-02 22:46:49 +00002312MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
2313
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002314/// Walk the use-def chains starting at \p StartingAccess and find
George Burgess IVe1100f52016-02-02 22:46:49 +00002315/// the MemoryAccess that actually clobbers Loc.
2316///
2317/// \returns our clobbering memory access
Alina Sbirleabfc779e2019-03-22 17:22:19 +00002318template <typename AliasAnalysisType>
2319MemoryAccess *
2320MemorySSA::ClobberWalkerBase<AliasAnalysisType>::getClobberingMemoryAccessBase(
Alina Sbirleaf085cc52019-03-29 21:56:09 +00002321 MemoryAccess *StartingAccess, const MemoryLocation &Loc,
2322 unsigned &UpwardWalkLimit) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002323 if (isa<MemoryPhi>(StartingAccess))
2324 return StartingAccess;
2325
2326 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
2327 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
2328 return StartingUseOrDef;
2329
2330 Instruction *I = StartingUseOrDef->getMemoryInst();
2331
2332 // Conservatively, fences are always clobbers, so don't perform the walk if we
2333 // hit a fence.
Chandler Carruth363ac682019-01-07 05:42:51 +00002334 if (!isa<CallBase>(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002335 return StartingUseOrDef;
2336
2337 UpwardsMemoryQuery Q;
2338 Q.OriginalAccess = StartingUseOrDef;
2339 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00002340 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00002341 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00002342
George Burgess IVe1100f52016-02-02 22:46:49 +00002343 // Unlike the other function, do not walk to the def of a def, because we are
2344 // handed something we already believe is the clobbering access.
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002345 // We never set SkipSelf to true in Q in this method.
George Burgess IVe1100f52016-02-02 22:46:49 +00002346 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
2347 ? StartingUseOrDef->getDefiningAccess()
2348 : StartingUseOrDef;
2349
Alina Sbirleaf085cc52019-03-29 21:56:09 +00002350 MemoryAccess *Clobber =
2351 Walker.findClobber(DefiningAccess, Q, UpwardWalkLimit);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002352 LLVM_DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2353 LLVM_DEBUG(dbgs() << *StartingUseOrDef << "\n");
2354 LLVM_DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2355 LLVM_DEBUG(dbgs() << *Clobber << "\n");
George Burgess IVe1100f52016-02-02 22:46:49 +00002356 return Clobber;
2357}
2358
Alina Sbirleabfc779e2019-03-22 17:22:19 +00002359template <typename AliasAnalysisType>
George Burgess IVe1100f52016-02-02 22:46:49 +00002360MemoryAccess *
Alina Sbirleabfc779e2019-03-22 17:22:19 +00002361MemorySSA::ClobberWalkerBase<AliasAnalysisType>::getClobberingMemoryAccessBase(
Alina Sbirleaf085cc52019-03-29 21:56:09 +00002362 MemoryAccess *MA, unsigned &UpwardWalkLimit, bool SkipSelf) {
George Burgess IV400ae402016-07-20 19:51:34 +00002363 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2364 // If this is a MemoryPhi, we can't do anything.
2365 if (!StartingAccess)
2366 return MA;
George Burgess IVe1100f52016-02-02 22:46:49 +00002367
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002368 bool IsOptimized = false;
2369
Daniel Berlincd2deac2016-10-20 20:13:45 +00002370 // If this is an already optimized use or def, return the optimized result.
Alina Sbirlead90c9f42018-03-08 18:03:14 +00002371 // Note: Currently, we store the optimized def result in a separate field,
2372 // since we can't use the defining access.
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002373 if (StartingAccess->isOptimized()) {
2374 if (!SkipSelf || !isa<MemoryDef>(StartingAccess))
2375 return StartingAccess->getOptimized();
2376 IsOptimized = true;
2377 }
Daniel Berlincd2deac2016-10-20 20:13:45 +00002378
George Burgess IV400ae402016-07-20 19:51:34 +00002379 const Instruction *I = StartingAccess->getMemoryInst();
George Burgess IV44477c62018-03-11 04:16:12 +00002380 // We can't sanely do anything with a fence, since they conservatively clobber
2381 // all memory, and have no locations to get pointers from to try to
2382 // disambiguate.
Chandler Carruth363ac682019-01-07 05:42:51 +00002383 if (!isa<CallBase>(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002384 return StartingAccess;
2385
Alina Sbirleab4d088d2018-11-13 21:12:49 +00002386 UpwardsMemoryQuery Q(I, StartingAccess);
2387
Alina Sbirleabfc779e2019-03-22 17:22:19 +00002388 if (isUseTriviallyOptimizableToLiveOnEntry(*Walker.getAA(), I)) {
George Burgess IV024f3d22016-08-03 19:57:02 +00002389 MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
George Burgess IV44477c62018-03-11 04:16:12 +00002390 StartingAccess->setOptimized(LiveOnEntry);
2391 StartingAccess->setOptimizedAccessType(None);
George Burgess IV024f3d22016-08-03 19:57:02 +00002392 return LiveOnEntry;
2393 }
2394
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002395 MemoryAccess *OptimizedAccess;
2396 if (!IsOptimized) {
2397 // Start with the thing we already think clobbers this location
2398 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
George Burgess IVe1100f52016-02-02 22:46:49 +00002399
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002400 // At this point, DefiningAccess may be the live on entry def.
2401 // If it is, we will not get a better result.
2402 if (MSSA->isLiveOnEntryDef(DefiningAccess)) {
2403 StartingAccess->setOptimized(DefiningAccess);
2404 StartingAccess->setOptimizedAccessType(None);
2405 return DefiningAccess;
2406 }
George Burgess IVe1100f52016-02-02 22:46:49 +00002407
Alina Sbirleaf085cc52019-03-29 21:56:09 +00002408 OptimizedAccess = Walker.findClobber(DefiningAccess, Q, UpwardWalkLimit);
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002409 StartingAccess->setOptimized(OptimizedAccess);
2410 if (MSSA->isLiveOnEntryDef(OptimizedAccess))
2411 StartingAccess->setOptimizedAccessType(None);
2412 else if (Q.AR == MustAlias)
2413 StartingAccess->setOptimizedAccessType(MustAlias);
2414 } else
2415 OptimizedAccess = StartingAccess->getOptimized();
2416
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002417 LLVM_DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002418 LLVM_DEBUG(dbgs() << *StartingAccess << "\n");
2419 LLVM_DEBUG(dbgs() << "Optimized Memory SSA clobber for " << *I << " is ");
2420 LLVM_DEBUG(dbgs() << *OptimizedAccess << "\n");
Alina Sbirlead90c9f42018-03-08 18:03:14 +00002421
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002422 MemoryAccess *Result;
2423 if (SkipSelf && isa<MemoryPhi>(OptimizedAccess) &&
Alina Sbirleaf085cc52019-03-29 21:56:09 +00002424 isa<MemoryDef>(StartingAccess) && UpwardWalkLimit) {
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002425 assert(isa<MemoryDef>(Q.OriginalAccess));
2426 Q.SkipSelfAccess = true;
Alina Sbirleaf085cc52019-03-29 21:56:09 +00002427 Result = Walker.findClobber(OptimizedAccess, Q, UpwardWalkLimit);
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002428 } else
2429 Result = OptimizedAccess;
2430
2431 LLVM_DEBUG(dbgs() << "Result Memory SSA clobber [SkipSelf = " << SkipSelf);
2432 LLVM_DEBUG(dbgs() << "] for " << *I << " is " << *Result << "\n");
George Burgess IVe1100f52016-02-02 22:46:49 +00002433
2434 return Result;
2435}
2436
George Burgess IVe1100f52016-02-02 22:46:49 +00002437MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002438DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002439 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2440 return Use->getDefiningAccess();
2441 return MA;
2442}
2443
2444MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
George Burgess IV013fd732016-10-28 19:22:46 +00002445 MemoryAccess *StartingAccess, const MemoryLocation &) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002446 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2447 return Use->getDefiningAccess();
2448 return StartingAccess;
2449}
Reid Kleckner96ab8722017-05-18 17:24:10 +00002450
2451void MemoryPhi::deleteMe(DerivedUser *Self) {
2452 delete static_cast<MemoryPhi *>(Self);
2453}
2454
2455void MemoryDef::deleteMe(DerivedUser *Self) {
2456 delete static_cast<MemoryDef *>(Self);
2457}
2458
2459void MemoryUse::deleteMe(DerivedUser *Self) {
2460 delete static_cast<MemoryUse *>(Self);
2461}