blob: ed2208eb2b48862174e7f9a4c3eacb28ff07e8c5 [file] [log] [blame]
George Burgess IVe1100f52016-02-02 22:46:49 +00001//===-- MemorySSA.cpp - Memory SSA Builder---------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------===//
9//
10// This file implements the MemorySSA class.
11//
12//===----------------------------------------------------------------===//
Daniel Berlin16ed57c2016-06-27 18:22:27 +000013#include "llvm/Transforms/Utils/MemorySSA.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000014#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/DenseSet.h"
16#include "llvm/ADT/DepthFirstIterator.h"
17#include "llvm/ADT/GraphTraits.h"
18#include "llvm/ADT/PostOrderIterator.h"
19#include "llvm/ADT/STLExtras.h"
George Burgess IV5f308972016-07-19 01:29:15 +000020#include "llvm/ADT/SmallBitVector.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000021#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/Analysis/AliasAnalysis.h"
25#include "llvm/Analysis/CFG.h"
26#include "llvm/Analysis/GlobalsModRef.h"
27#include "llvm/Analysis/IteratedDominanceFrontier.h"
28#include "llvm/Analysis/MemoryLocation.h"
29#include "llvm/Analysis/PHITransAddr.h"
30#include "llvm/IR/AssemblyAnnotationWriter.h"
31#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/Dominators.h"
33#include "llvm/IR/GlobalVariable.h"
34#include "llvm/IR/IRBuilder.h"
35#include "llvm/IR/IntrinsicInst.h"
36#include "llvm/IR/LLVMContext.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
39#include "llvm/IR/PatternMatch.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000040#include "llvm/Support/Debug.h"
41#include "llvm/Support/FormattedStream.h"
42#include "llvm/Transforms/Scalar.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000043#include <algorithm>
44
45#define DEBUG_TYPE "memoryssa"
46using namespace llvm;
47STATISTIC(NumClobberCacheLookups, "Number of Memory SSA version cache lookups");
48STATISTIC(NumClobberCacheHits, "Number of Memory SSA version cache hits");
49STATISTIC(NumClobberCacheInserts, "Number of MemorySSA version cache inserts");
Geoff Berryb96d3b22016-06-01 21:30:40 +000050
Geoff Berryefb0dd12016-06-14 21:19:40 +000051INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
Geoff Berryb96d3b22016-06-01 21:30:40 +000052 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000053INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
54INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Geoff Berryefb0dd12016-06-14 21:19:40 +000055INITIALIZE_PASS_END(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
56 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000057
Chad Rosier232e29e2016-07-06 21:20:47 +000058INITIALIZE_PASS_BEGIN(MemorySSAPrinterLegacyPass, "print-memoryssa",
59 "Memory SSA Printer", false, false)
60INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
61INITIALIZE_PASS_END(MemorySSAPrinterLegacyPass, "print-memoryssa",
62 "Memory SSA Printer", false, false)
63
Daniel Berlinc43aa5a2016-08-02 16:24:03 +000064static cl::opt<unsigned> MaxCheckLimit(
65 "memssa-check-limit", cl::Hidden, cl::init(100),
66 cl::desc("The maximum number of stores/phis MemorySSA"
67 "will consider trying to walk past (default = 100)"));
68
Chad Rosier232e29e2016-07-06 21:20:47 +000069static cl::opt<bool>
70 VerifyMemorySSA("verify-memoryssa", cl::init(false), cl::Hidden,
71 cl::desc("Verify MemorySSA in legacy printer pass."));
72
George Burgess IVe1100f52016-02-02 22:46:49 +000073namespace llvm {
George Burgess IVe1100f52016-02-02 22:46:49 +000074/// \brief An assembly annotator class to print Memory SSA information in
75/// comments.
76class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
77 friend class MemorySSA;
78 const MemorySSA *MSSA;
79
80public:
81 MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
82
83 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
84 formatted_raw_ostream &OS) {
85 if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
86 OS << "; " << *MA << "\n";
87 }
88
89 virtual void emitInstructionAnnot(const Instruction *I,
90 formatted_raw_ostream &OS) {
91 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
92 OS << "; " << *MA << "\n";
93 }
94};
George Burgess IV5f308972016-07-19 01:29:15 +000095}
George Burgess IVfd1f2f82016-06-24 21:02:12 +000096
George Burgess IV5f308972016-07-19 01:29:15 +000097namespace {
Daniel Berlindff31de2016-08-02 21:57:52 +000098/// Our current alias analysis API differentiates heavily between calls and
99/// non-calls, and functions called on one usually assert on the other.
100/// This class encapsulates the distinction to simplify other code that wants
101/// "Memory affecting instructions and related data" to use as a key.
102/// For example, this class is used as a densemap key in the use optimizer.
103class MemoryLocOrCall {
104public:
105 MemoryLocOrCall() : IsCall(false) {}
106 MemoryLocOrCall(MemoryUseOrDef *MUD)
107 : MemoryLocOrCall(MUD->getMemoryInst()) {}
108
109 MemoryLocOrCall(Instruction *Inst) {
110 if (ImmutableCallSite(Inst)) {
111 IsCall = true;
112 CS = ImmutableCallSite(Inst);
113 } else {
114 IsCall = false;
115 // There is no such thing as a memorylocation for a fence inst, and it is
116 // unique in that regard.
117 if (!isa<FenceInst>(Inst))
118 Loc = MemoryLocation::get(Inst);
119 }
120 }
121
122 explicit MemoryLocOrCall(const MemoryLocation &Loc)
123 : IsCall(false), Loc(Loc) {}
124
125 bool IsCall;
126 ImmutableCallSite getCS() const {
127 assert(IsCall);
128 return CS;
129 }
130 MemoryLocation getLoc() const {
131 assert(!IsCall);
132 return Loc;
133 }
134
135 bool operator==(const MemoryLocOrCall &Other) const {
136 if (IsCall != Other.IsCall)
137 return false;
138
139 if (IsCall)
140 return CS.getCalledValue() == Other.CS.getCalledValue();
141 return Loc == Other.Loc;
142 }
143
144private:
145 // FIXME: MSVC 2013 does not properly implement C++11 union rules, once we
146 // require newer versions, this should be made an anonymous union again.
147 ImmutableCallSite CS;
148 MemoryLocation Loc;
149};
150}
151
152namespace llvm {
153template <> struct DenseMapInfo<MemoryLocOrCall> {
154 static inline MemoryLocOrCall getEmptyKey() {
155 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getEmptyKey());
156 }
157 static inline MemoryLocOrCall getTombstoneKey() {
158 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getTombstoneKey());
159 }
160 static unsigned getHashValue(const MemoryLocOrCall &MLOC) {
161 if (MLOC.IsCall)
162 return hash_combine(MLOC.IsCall,
163 DenseMapInfo<const Value *>::getHashValue(
164 MLOC.getCS().getCalledValue()));
165 return hash_combine(
166 MLOC.IsCall, DenseMapInfo<MemoryLocation>::getHashValue(MLOC.getLoc()));
167 }
168 static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS) {
169 return LHS == RHS;
170 }
171};
Daniel Berlindf101192016-08-03 00:01:46 +0000172
George Burgess IVf7672852016-08-03 19:59:11 +0000173enum class Reorderability { Always, IfNoAlias, Never };
George Burgess IV82e355c2016-08-03 19:39:54 +0000174
175/// This does one-way checks to see if Use could theoretically be hoisted above
176/// MayClobber. This will not check the other way around.
177///
178/// This assumes that, for the purposes of MemorySSA, Use comes directly after
179/// MayClobber, with no potentially clobbering operations in between them.
180/// (Where potentially clobbering ops are memory barriers, aliased stores, etc.)
181static Reorderability getLoadReorderability(const LoadInst *Use,
182 const LoadInst *MayClobber) {
183 bool VolatileUse = Use->isVolatile();
184 bool VolatileClobber = MayClobber->isVolatile();
185 // Volatile operations may never be reordered with other volatile operations.
186 if (VolatileUse && VolatileClobber)
187 return Reorderability::Never;
188
189 // The lang ref allows reordering of volatile and non-volatile operations.
190 // Whether an aliasing nonvolatile load and volatile load can be reordered,
191 // though, is ambiguous. Because it may not be best to exploit this ambiguity,
192 // we only allow volatile/non-volatile reordering if the volatile and
193 // non-volatile operations don't alias.
194 Reorderability Result = VolatileUse || VolatileClobber
195 ? Reorderability::IfNoAlias
196 : Reorderability::Always;
197
198 // If a load is seq_cst, it cannot be moved above other loads. If its ordering
199 // is weaker, it can be moved above other loads. We just need to be sure that
200 // MayClobber isn't an acquire load, because loads can't be moved above
201 // acquire loads.
202 //
203 // Note that this explicitly *does* allow the free reordering of monotonic (or
204 // weaker) loads of the same address.
205 bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent;
206 bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(),
207 AtomicOrdering::Acquire);
208 if (SeqCstUse || MayClobberIsAcquire)
209 return Reorderability::Never;
210 return Result;
211}
212
Sebastian Popd57d93c2016-10-12 03:08:40 +0000213static bool instructionClobbersQuery(MemoryDef *MD,
214 const MemoryLocation &UseLoc,
215 const Instruction *UseInst,
216 AliasAnalysis &AA) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000217 Instruction *DefInst = MD->getMemoryInst();
218 assert(DefInst && "Defining instruction not actually an instruction");
George Burgess IV5f308972016-07-19 01:29:15 +0000219
Daniel Berlindf101192016-08-03 00:01:46 +0000220 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
221 // These intrinsics will show up as affecting memory, but they are just
222 // markers.
223 switch (II->getIntrinsicID()) {
224 case Intrinsic::lifetime_start:
225 case Intrinsic::lifetime_end:
226 case Intrinsic::invariant_start:
227 case Intrinsic::invariant_end:
228 case Intrinsic::assume:
229 return false;
230 default:
231 break;
232 }
233 }
234
Daniel Berlindff31de2016-08-02 21:57:52 +0000235 ImmutableCallSite UseCS(UseInst);
236 if (UseCS) {
237 ModRefInfo I = AA.getModRefInfo(DefInst, UseCS);
238 return I != MRI_NoModRef;
239 }
George Burgess IV82e355c2016-08-03 19:39:54 +0000240
241 if (auto *DefLoad = dyn_cast<LoadInst>(DefInst)) {
242 if (auto *UseLoad = dyn_cast<LoadInst>(UseInst)) {
243 switch (getLoadReorderability(UseLoad, DefLoad)) {
244 case Reorderability::Always:
245 return false;
246 case Reorderability::Never:
247 return true;
248 case Reorderability::IfNoAlias:
249 return !AA.isNoAlias(UseLoc, MemoryLocation::get(DefLoad));
250 }
251 }
252 }
253
Daniel Berlindff31de2016-08-02 21:57:52 +0000254 return AA.getModRefInfo(DefInst, UseLoc) & MRI_Mod;
255}
256
Sebastian Popd57d93c2016-10-12 03:08:40 +0000257// Return true when MD may alias MU, return false otherwise.
258bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
259 AliasAnalysis &AA) {
260 Instruction *Insn = MU->getMemoryInst();
261 return instructionClobbersQuery(MD, MemoryLocation::get(Insn), Insn, AA);
262}
Sebastian Popab12fb62016-10-12 02:23:39 +0000263}
264
265namespace {
266struct UpwardsMemoryQuery {
267 // True if our original query started off as a call
268 bool IsCall;
269 // The pointer location we started the query with. This will be empty if
270 // IsCall is true.
271 MemoryLocation StartingLoc;
272 // This is the instruction we were querying about.
273 const Instruction *Inst;
274 // The MemoryAccess we actually got called with, used to test local domination
275 const MemoryAccess *OriginalAccess;
276
277 UpwardsMemoryQuery()
278 : IsCall(false), Inst(nullptr), OriginalAccess(nullptr) {}
279
280 UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
281 : IsCall(ImmutableCallSite(Inst)), Inst(Inst), OriginalAccess(Access) {
282 if (!IsCall)
283 StartingLoc = MemoryLocation::get(Inst);
284 }
285};
286
287static bool lifetimeEndsAt(MemoryDef *MD, const MemoryLocation &Loc,
288 AliasAnalysis &AA) {
289 Instruction *Inst = MD->getMemoryInst();
290 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
291 switch (II->getIntrinsicID()) {
292 case Intrinsic::lifetime_start:
293 case Intrinsic::lifetime_end:
294 return AA.isMustAlias(MemoryLocation(II->getArgOperand(1)), Loc);
295 default:
296 return false;
297 }
298 }
299 return false;
300}
301
302static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysis &AA,
303 const Instruction *I) {
304 // If the memory can't be changed, then loads of the memory can't be
305 // clobbered.
306 //
307 // FIXME: We should handle invariant groups, as well. It's a bit harder,
308 // because we need to pay close attention to invariant group barriers.
309 return isa<LoadInst>(I) && (I->getMetadata(LLVMContext::MD_invariant_load) ||
310 AA.pointsToConstantMemory(I));
311}
312
Daniel Berlindff31de2016-08-02 21:57:52 +0000313static bool instructionClobbersQuery(MemoryDef *MD, MemoryUse *MU,
314 const MemoryLocOrCall &UseMLOC,
315 AliasAnalysis &AA) {
316 // FIXME: This is a temporary hack to allow a single instructionClobbersQuery
317 // to exist while MemoryLocOrCall is pushed through places.
318 if (UseMLOC.IsCall)
319 return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(),
320 AA);
321 return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(),
322 AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000323}
324
325/// Cache for our caching MemorySSA walker.
326class WalkerCache {
327 DenseMap<ConstMemoryAccessPair, MemoryAccess *> Accesses;
328 DenseMap<const MemoryAccess *, MemoryAccess *> Calls;
329
330public:
331 MemoryAccess *lookup(const MemoryAccess *MA, const MemoryLocation &Loc,
332 bool IsCall) const {
333 ++NumClobberCacheLookups;
334 MemoryAccess *R = IsCall ? Calls.lookup(MA) : Accesses.lookup({MA, Loc});
335 if (R)
336 ++NumClobberCacheHits;
337 return R;
338 }
339
340 bool insert(const MemoryAccess *MA, MemoryAccess *To,
341 const MemoryLocation &Loc, bool IsCall) {
342 // This is fine for Phis, since there are times where we can't optimize
343 // them. Making a def its own clobber is never correct, though.
344 assert((MA != To || isa<MemoryPhi>(MA)) &&
345 "Something can't clobber itself!");
346
347 ++NumClobberCacheInserts;
348 bool Inserted;
349 if (IsCall)
350 Inserted = Calls.insert({MA, To}).second;
351 else
352 Inserted = Accesses.insert({{MA, Loc}, To}).second;
353
354 return Inserted;
355 }
356
357 bool remove(const MemoryAccess *MA, const MemoryLocation &Loc, bool IsCall) {
358 return IsCall ? Calls.erase(MA) : Accesses.erase({MA, Loc});
359 }
360
361 void clear() {
362 Accesses.clear();
363 Calls.clear();
364 }
365
366 bool contains(const MemoryAccess *MA) const {
367 for (auto &P : Accesses)
368 if (P.first.first == MA || P.second == MA)
369 return true;
370 for (auto &P : Calls)
371 if (P.first == MA || P.second == MA)
372 return true;
373 return false;
374 }
375};
376
377/// Walks the defining uses of MemoryDefs. Stops after we hit something that has
378/// no defining use (e.g. a MemoryPhi or liveOnEntry). Note that, when comparing
379/// against a null def_chain_iterator, this will compare equal only after
380/// walking said Phi/liveOnEntry.
381struct def_chain_iterator
382 : public iterator_facade_base<def_chain_iterator, std::forward_iterator_tag,
383 MemoryAccess *> {
384 def_chain_iterator() : MA(nullptr) {}
385 def_chain_iterator(MemoryAccess *MA) : MA(MA) {}
386
387 MemoryAccess *operator*() const { return MA; }
388
389 def_chain_iterator &operator++() {
390 // N.B. liveOnEntry has a null defining access.
391 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
392 MA = MUD->getDefiningAccess();
393 else
394 MA = nullptr;
395 return *this;
396 }
397
398 bool operator==(const def_chain_iterator &O) const { return MA == O.MA; }
399
400private:
401 MemoryAccess *MA;
402};
403
404static iterator_range<def_chain_iterator>
405def_chain(MemoryAccess *MA, MemoryAccess *UpTo = nullptr) {
406#ifdef EXPENSIVE_CHECKS
407 assert((!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator()) &&
408 "UpTo isn't in the def chain!");
409#endif
410 return make_range(def_chain_iterator(MA), def_chain_iterator(UpTo));
411}
412
413/// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
414/// inbetween `Start` and `ClobberAt` can clobbers `Start`.
415///
416/// This is meant to be as simple and self-contained as possible. Because it
417/// uses no cache, etc., it can be relatively expensive.
418///
419/// \param Start The MemoryAccess that we want to walk from.
420/// \param ClobberAt A clobber for Start.
421/// \param StartLoc The MemoryLocation for Start.
422/// \param MSSA The MemorySSA isntance that Start and ClobberAt belong to.
423/// \param Query The UpwardsMemoryQuery we used for our search.
424/// \param AA The AliasAnalysis we used for our search.
425static void LLVM_ATTRIBUTE_UNUSED
426checkClobberSanity(MemoryAccess *Start, MemoryAccess *ClobberAt,
427 const MemoryLocation &StartLoc, const MemorySSA &MSSA,
428 const UpwardsMemoryQuery &Query, AliasAnalysis &AA) {
429 assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
430
431 if (MSSA.isLiveOnEntryDef(Start)) {
432 assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
433 "liveOnEntry must clobber itself");
434 return;
435 }
436
George Burgess IV5f308972016-07-19 01:29:15 +0000437 bool FoundClobber = false;
438 DenseSet<MemoryAccessPair> VisitedPhis;
439 SmallVector<MemoryAccessPair, 8> Worklist;
440 Worklist.emplace_back(Start, StartLoc);
441 // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
442 // is found, complain.
443 while (!Worklist.empty()) {
444 MemoryAccessPair MAP = Worklist.pop_back_val();
445 // All we care about is that nothing from Start to ClobberAt clobbers Start.
446 // We learn nothing from revisiting nodes.
447 if (!VisitedPhis.insert(MAP).second)
448 continue;
449
450 for (MemoryAccess *MA : def_chain(MAP.first)) {
451 if (MA == ClobberAt) {
452 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
453 // instructionClobbersQuery isn't essentially free, so don't use `|=`,
454 // since it won't let us short-circuit.
455 //
456 // Also, note that this can't be hoisted out of the `Worklist` loop,
457 // since MD may only act as a clobber for 1 of N MemoryLocations.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000458 FoundClobber =
459 FoundClobber || MSSA.isLiveOnEntryDef(MD) ||
460 instructionClobbersQuery(MD, MAP.second, Query.Inst, AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000461 }
462 break;
463 }
464
465 // We should never hit liveOnEntry, unless it's the clobber.
466 assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
467
468 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
469 (void)MD;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000470 assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA) &&
George Burgess IV5f308972016-07-19 01:29:15 +0000471 "Found clobber before reaching ClobberAt!");
472 continue;
473 }
474
475 assert(isa<MemoryPhi>(MA));
476 Worklist.append(upward_defs_begin({MA, MAP.second}), upward_defs_end());
477 }
478 }
479
480 // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
481 // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
482 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
483 "ClobberAt never acted as a clobber");
484}
485
486/// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
487/// in one class.
488class ClobberWalker {
489 /// Save a few bytes by using unsigned instead of size_t.
490 using ListIndex = unsigned;
491
492 /// Represents a span of contiguous MemoryDefs, potentially ending in a
493 /// MemoryPhi.
494 struct DefPath {
495 MemoryLocation Loc;
496 // Note that, because we always walk in reverse, Last will always dominate
497 // First. Also note that First and Last are inclusive.
498 MemoryAccess *First;
499 MemoryAccess *Last;
George Burgess IV5f308972016-07-19 01:29:15 +0000500 Optional<ListIndex> Previous;
501
502 DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
503 Optional<ListIndex> Previous)
504 : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
505
506 DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
507 Optional<ListIndex> Previous)
508 : DefPath(Loc, Init, Init, Previous) {}
509 };
510
511 const MemorySSA &MSSA;
512 AliasAnalysis &AA;
513 DominatorTree &DT;
514 WalkerCache &WC;
515 UpwardsMemoryQuery *Query;
516 bool UseCache;
517
518 // Phi optimization bookkeeping
519 SmallVector<DefPath, 32> Paths;
520 DenseSet<ConstMemoryAccessPair> VisitedPhis;
521 DenseMap<const BasicBlock *, MemoryAccess *> WalkTargetCache;
522
523 void setUseCache(bool Use) { UseCache = Use; }
524 bool shouldIgnoreCache() const {
525 // UseCache will only be false when we're debugging, or when expensive
526 // checks are enabled. In either case, we don't care deeply about speed.
527 return LLVM_UNLIKELY(!UseCache);
528 }
529
530 void addCacheEntry(const MemoryAccess *What, MemoryAccess *To,
531 const MemoryLocation &Loc) const {
Daniel Berlin5c46b942016-07-19 22:49:43 +0000532// EXPENSIVE_CHECKS because most of these queries are redundant.
George Burgess IV5f308972016-07-19 01:29:15 +0000533#ifdef EXPENSIVE_CHECKS
534 assert(MSSA.dominates(To, What));
535#endif
536 if (shouldIgnoreCache())
537 return;
538 WC.insert(What, To, Loc, Query->IsCall);
539 }
540
541 MemoryAccess *lookupCache(const MemoryAccess *MA, const MemoryLocation &Loc) {
542 return shouldIgnoreCache() ? nullptr : WC.lookup(MA, Loc, Query->IsCall);
543 }
544
545 void cacheDefPath(const DefPath &DN, MemoryAccess *Target) const {
546 if (shouldIgnoreCache())
547 return;
548
549 for (MemoryAccess *MA : def_chain(DN.First, DN.Last))
550 addCacheEntry(MA, Target, DN.Loc);
551
552 // DefPaths only express the path we walked. So, DN.Last could either be a
553 // thing we want to cache, or not.
554 if (DN.Last != Target)
555 addCacheEntry(DN.Last, Target, DN.Loc);
556 }
557
558 /// Find the nearest def or phi that `From` can legally be optimized to.
559 ///
560 /// FIXME: Deduplicate this with MSSA::findDominatingDef. Ideally, MSSA should
561 /// keep track of this information for us, and allow us O(1) lookups of this
562 /// info.
563 MemoryAccess *getWalkTarget(const MemoryPhi *From) {
George Burgess IV5f308972016-07-19 01:29:15 +0000564 assert(From->getNumOperands() && "Phi with no operands?");
565
566 BasicBlock *BB = From->getBlock();
567 auto At = WalkTargetCache.find(BB);
568 if (At != WalkTargetCache.end())
569 return At->second;
570
571 SmallVector<const BasicBlock *, 8> ToCache;
572 ToCache.push_back(BB);
573
574 MemoryAccess *Result = MSSA.getLiveOnEntryDef();
575 DomTreeNode *Node = DT.getNode(BB);
576 while ((Node = Node->getIDom())) {
577 auto At = WalkTargetCache.find(BB);
578 if (At != WalkTargetCache.end()) {
579 Result = At->second;
580 break;
581 }
582
583 auto *Accesses = MSSA.getBlockAccesses(Node->getBlock());
584 if (Accesses) {
585 auto Iter = find_if(reverse(*Accesses), [](const MemoryAccess &MA) {
586 return !isa<MemoryUse>(MA);
587 });
588 if (Iter != Accesses->rend()) {
589 Result = const_cast<MemoryAccess *>(&*Iter);
590 break;
591 }
592 }
593
594 ToCache.push_back(Node->getBlock());
595 }
596
597 for (const BasicBlock *BB : ToCache)
598 WalkTargetCache.insert({BB, Result});
599 return Result;
600 }
601
602 /// Result of calling walkToPhiOrClobber.
603 struct UpwardsWalkResult {
604 /// The "Result" of the walk. Either a clobber, the last thing we walked, or
605 /// both.
606 MemoryAccess *Result;
607 bool IsKnownClobber;
608 bool FromCache;
609 };
610
611 /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
612 /// This will update Desc.Last as it walks. It will (optionally) also stop at
613 /// StopAt.
614 ///
615 /// This does not test for whether StopAt is a clobber
616 UpwardsWalkResult walkToPhiOrClobber(DefPath &Desc,
617 MemoryAccess *StopAt = nullptr) {
618 assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
619
620 for (MemoryAccess *Current : def_chain(Desc.Last)) {
621 Desc.Last = Current;
622 if (Current == StopAt)
623 return {Current, false, false};
624
625 if (auto *MD = dyn_cast<MemoryDef>(Current))
626 if (MSSA.isLiveOnEntryDef(MD) ||
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000627 instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA))
George Burgess IV5f308972016-07-19 01:29:15 +0000628 return {MD, true, false};
629
630 // Cache checks must be done last, because if Current is a clobber, the
631 // cache will contain the clobber for Current.
632 if (MemoryAccess *MA = lookupCache(Current, Desc.Loc))
633 return {MA, true, true};
634 }
635
636 assert(isa<MemoryPhi>(Desc.Last) &&
637 "Ended at a non-clobber that's not a phi?");
638 return {Desc.Last, false, false};
639 }
640
641 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
642 ListIndex PriorNode) {
643 auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),
644 upward_defs_end());
645 for (const MemoryAccessPair &P : UpwardDefs) {
646 PausedSearches.push_back(Paths.size());
647 Paths.emplace_back(P.second, P.first, PriorNode);
648 }
649 }
650
651 /// Represents a search that terminated after finding a clobber. This clobber
652 /// may or may not be present in the path of defs from LastNode..SearchStart,
653 /// since it may have been retrieved from cache.
654 struct TerminatedPath {
655 MemoryAccess *Clobber;
656 ListIndex LastNode;
657 };
658
659 /// Get an access that keeps us from optimizing to the given phi.
660 ///
661 /// PausedSearches is an array of indices into the Paths array. Its incoming
662 /// value is the indices of searches that stopped at the last phi optimization
663 /// target. It's left in an unspecified state.
664 ///
665 /// If this returns None, NewPaused is a vector of searches that terminated
666 /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
George Burgess IV14633b52016-08-03 01:22:19 +0000667 Optional<TerminatedPath>
George Burgess IV5f308972016-07-19 01:29:15 +0000668 getBlockingAccess(MemoryAccess *StopWhere,
669 SmallVectorImpl<ListIndex> &PausedSearches,
670 SmallVectorImpl<ListIndex> &NewPaused,
671 SmallVectorImpl<TerminatedPath> &Terminated) {
672 assert(!PausedSearches.empty() && "No searches to continue?");
673
674 // BFS vs DFS really doesn't make a difference here, so just do a DFS with
675 // PausedSearches as our stack.
676 while (!PausedSearches.empty()) {
677 ListIndex PathIndex = PausedSearches.pop_back_val();
678 DefPath &Node = Paths[PathIndex];
679
680 // If we've already visited this path with this MemoryLocation, we don't
681 // need to do so again.
682 //
683 // NOTE: That we just drop these paths on the ground makes caching
684 // behavior sporadic. e.g. given a diamond:
685 // A
686 // B C
687 // D
688 //
689 // ...If we walk D, B, A, C, we'll only cache the result of phi
690 // optimization for A, B, and D; C will be skipped because it dies here.
691 // This arguably isn't the worst thing ever, since:
692 // - We generally query things in a top-down order, so if we got below D
693 // without needing cache entries for {C, MemLoc}, then chances are
694 // that those cache entries would end up ultimately unused.
695 // - We still cache things for A, so C only needs to walk up a bit.
696 // If this behavior becomes problematic, we can fix without a ton of extra
697 // work.
698 if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
699 continue;
700
701 UpwardsWalkResult Res = walkToPhiOrClobber(Node, /*StopAt=*/StopWhere);
702 if (Res.IsKnownClobber) {
703 assert(Res.Result != StopWhere || Res.FromCache);
704 // If this wasn't a cache hit, we hit a clobber when walking. That's a
705 // failure.
George Burgess IV14633b52016-08-03 01:22:19 +0000706 TerminatedPath Term{Res.Result, PathIndex};
George Burgess IV5f308972016-07-19 01:29:15 +0000707 if (!Res.FromCache || !MSSA.dominates(Res.Result, StopWhere))
George Burgess IV14633b52016-08-03 01:22:19 +0000708 return Term;
George Burgess IV5f308972016-07-19 01:29:15 +0000709
710 // Otherwise, it's a valid thing to potentially optimize to.
George Burgess IV14633b52016-08-03 01:22:19 +0000711 Terminated.push_back(Term);
George Burgess IV5f308972016-07-19 01:29:15 +0000712 continue;
713 }
714
715 if (Res.Result == StopWhere) {
716 // We've hit our target. Save this path off for if we want to continue
717 // walking.
718 NewPaused.push_back(PathIndex);
719 continue;
720 }
721
722 assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
723 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
724 }
725
726 return None;
727 }
728
729 template <typename T, typename Walker>
730 struct generic_def_path_iterator
731 : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
732 std::forward_iterator_tag, T *> {
733 generic_def_path_iterator() : W(nullptr), N(None) {}
734 generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
735
736 T &operator*() const { return curNode(); }
737
738 generic_def_path_iterator &operator++() {
739 N = curNode().Previous;
740 return *this;
741 }
742
743 bool operator==(const generic_def_path_iterator &O) const {
744 if (N.hasValue() != O.N.hasValue())
745 return false;
746 return !N.hasValue() || *N == *O.N;
747 }
748
749 private:
750 T &curNode() const { return W->Paths[*N]; }
751
752 Walker *W;
753 Optional<ListIndex> N;
754 };
755
756 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
757 using const_def_path_iterator =
758 generic_def_path_iterator<const DefPath, const ClobberWalker>;
759
760 iterator_range<def_path_iterator> def_path(ListIndex From) {
761 return make_range(def_path_iterator(this, From), def_path_iterator());
762 }
763
764 iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
765 return make_range(const_def_path_iterator(this, From),
766 const_def_path_iterator());
767 }
768
769 struct OptznResult {
770 /// The path that contains our result.
771 TerminatedPath PrimaryClobber;
772 /// The paths that we can legally cache back from, but that aren't
773 /// necessarily the result of the Phi optimization.
774 SmallVector<TerminatedPath, 4> OtherClobbers;
775 };
776
777 ListIndex defPathIndex(const DefPath &N) const {
778 // The assert looks nicer if we don't need to do &N
779 const DefPath *NP = &N;
780 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
781 "Out of bounds DefPath!");
782 return NP - &Paths.front();
783 }
784
785 /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
786 /// that act as legal clobbers. Note that this won't return *all* clobbers.
787 ///
788 /// Phi optimization algorithm tl;dr:
789 /// - Find the earliest def/phi, A, we can optimize to
790 /// - Find if all paths from the starting memory access ultimately reach A
791 /// - If not, optimization isn't possible.
792 /// - Otherwise, walk from A to another clobber or phi, A'.
793 /// - If A' is a def, we're done.
794 /// - If A' is a phi, try to optimize it.
795 ///
796 /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
797 /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
798 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
799 const MemoryLocation &Loc) {
800 assert(Paths.empty() && VisitedPhis.empty() &&
801 "Reset the optimization state.");
802
803 Paths.emplace_back(Loc, Start, Phi, None);
804 // Stores how many "valid" optimization nodes we had prior to calling
805 // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
806 auto PriorPathsSize = Paths.size();
807
808 SmallVector<ListIndex, 16> PausedSearches;
809 SmallVector<ListIndex, 8> NewPaused;
810 SmallVector<TerminatedPath, 4> TerminatedPaths;
811
812 addSearches(Phi, PausedSearches, 0);
813
814 // Moves the TerminatedPath with the "most dominated" Clobber to the end of
815 // Paths.
816 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
817 assert(!Paths.empty() && "Need a path to move");
George Burgess IV5f308972016-07-19 01:29:15 +0000818 auto Dom = Paths.begin();
819 for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
820 if (!MSSA.dominates(I->Clobber, Dom->Clobber))
821 Dom = I;
822 auto Last = Paths.end() - 1;
823 if (Last != Dom)
824 std::iter_swap(Last, Dom);
825 };
826
827 MemoryPhi *Current = Phi;
828 while (1) {
829 assert(!MSSA.isLiveOnEntryDef(Current) &&
830 "liveOnEntry wasn't treated as a clobber?");
831
832 MemoryAccess *Target = getWalkTarget(Current);
833 // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
834 // optimization for the prior phi.
835 assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
836 return MSSA.dominates(P.Clobber, Target);
837 }));
838
839 // FIXME: This is broken, because the Blocker may be reported to be
840 // liveOnEntry, and we'll happily wait for that to disappear (read: never)
George Burgess IV7f414b92016-08-22 23:40:01 +0000841 // For the moment, this is fine, since we do nothing with blocker info.
George Burgess IV14633b52016-08-03 01:22:19 +0000842 if (Optional<TerminatedPath> Blocker = getBlockingAccess(
George Burgess IV5f308972016-07-19 01:29:15 +0000843 Target, PausedSearches, NewPaused, TerminatedPaths)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000844 // Cache our work on the blocking node, since we know that's correct.
George Burgess IV14633b52016-08-03 01:22:19 +0000845 cacheDefPath(Paths[Blocker->LastNode], Blocker->Clobber);
George Burgess IV5f308972016-07-19 01:29:15 +0000846
847 // Find the node we started at. We can't search based on N->Last, since
848 // we may have gone around a loop with a different MemoryLocation.
George Burgess IV14633b52016-08-03 01:22:19 +0000849 auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
George Burgess IV5f308972016-07-19 01:29:15 +0000850 return defPathIndex(N) < PriorPathsSize;
851 });
852 assert(Iter != def_path_iterator());
853
854 DefPath &CurNode = *Iter;
855 assert(CurNode.Last == Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000856
857 // Two things:
858 // A. We can't reliably cache all of NewPaused back. Consider a case
859 // where we have two paths in NewPaused; one of which can't optimize
860 // above this phi, whereas the other can. If we cache the second path
861 // back, we'll end up with suboptimal cache entries. We can handle
862 // cases like this a bit better when we either try to find all
863 // clobbers that block phi optimization, or when our cache starts
864 // supporting unfinished searches.
865 // B. We can't reliably cache TerminatedPaths back here without doing
866 // extra checks; consider a case like:
867 // T
868 // / \
869 // D C
870 // \ /
871 // S
872 // Where T is our target, C is a node with a clobber on it, D is a
873 // diamond (with a clobber *only* on the left or right node, N), and
874 // S is our start. Say we walk to D, through the node opposite N
875 // (read: ignoring the clobber), and see a cache entry in the top
876 // node of D. That cache entry gets put into TerminatedPaths. We then
877 // walk up to C (N is later in our worklist), find the clobber, and
878 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
879 // the bottom part of D to the cached clobber, ignoring the clobber
880 // in N. Again, this problem goes away if we start tracking all
881 // blockers for a given phi optimization.
882 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
883 return {Result, {}};
884 }
885
886 // If there's nothing left to search, then all paths led to valid clobbers
887 // that we got from our cache; pick the nearest to the start, and allow
888 // the rest to be cached back.
889 if (NewPaused.empty()) {
890 MoveDominatedPathToEnd(TerminatedPaths);
891 TerminatedPath Result = TerminatedPaths.pop_back_val();
892 return {Result, std::move(TerminatedPaths)};
893 }
894
895 MemoryAccess *DefChainEnd = nullptr;
896 SmallVector<TerminatedPath, 4> Clobbers;
897 for (ListIndex Paused : NewPaused) {
898 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
899 if (WR.IsKnownClobber)
900 Clobbers.push_back({WR.Result, Paused});
901 else
902 // Micro-opt: If we hit the end of the chain, save it.
903 DefChainEnd = WR.Result;
904 }
905
906 if (!TerminatedPaths.empty()) {
907 // If we couldn't find the dominating phi/liveOnEntry in the above loop,
908 // do it now.
909 if (!DefChainEnd)
910 for (MemoryAccess *MA : def_chain(Target))
911 DefChainEnd = MA;
912
913 // If any of the terminated paths don't dominate the phi we'll try to
914 // optimize, we need to figure out what they are and quit.
915 const BasicBlock *ChainBB = DefChainEnd->getBlock();
916 for (const TerminatedPath &TP : TerminatedPaths) {
917 // Because we know that DefChainEnd is as "high" as we can go, we
918 // don't need local dominance checks; BB dominance is sufficient.
919 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
920 Clobbers.push_back(TP);
921 }
922 }
923
924 // If we have clobbers in the def chain, find the one closest to Current
925 // and quit.
926 if (!Clobbers.empty()) {
927 MoveDominatedPathToEnd(Clobbers);
928 TerminatedPath Result = Clobbers.pop_back_val();
929 return {Result, std::move(Clobbers)};
930 }
931
932 assert(all_of(NewPaused,
933 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
934
935 // Because liveOnEntry is a clobber, this must be a phi.
936 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
937
938 PriorPathsSize = Paths.size();
939 PausedSearches.clear();
940 for (ListIndex I : NewPaused)
941 addSearches(DefChainPhi, PausedSearches, I);
942 NewPaused.clear();
943
944 Current = DefChainPhi;
945 }
946 }
947
948 /// Caches everything in an OptznResult.
949 void cacheOptResult(const OptznResult &R) {
950 if (R.OtherClobbers.empty()) {
951 // If we're not going to be caching OtherClobbers, don't bother with
952 // marking visited/etc.
953 for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode))
954 cacheDefPath(N, R.PrimaryClobber.Clobber);
955 return;
956 }
957
958 // PrimaryClobber is our answer. If we can cache anything back, we need to
959 // stop caching when we visit PrimaryClobber.
960 SmallBitVector Visited(Paths.size());
961 for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode)) {
962 Visited[defPathIndex(N)] = true;
963 cacheDefPath(N, R.PrimaryClobber.Clobber);
964 }
965
966 for (const TerminatedPath &P : R.OtherClobbers) {
967 for (const DefPath &N : const_def_path(P.LastNode)) {
968 ListIndex NIndex = defPathIndex(N);
969 if (Visited[NIndex])
970 break;
971 Visited[NIndex] = true;
972 cacheDefPath(N, P.Clobber);
973 }
974 }
975 }
976
977 void verifyOptResult(const OptznResult &R) const {
978 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
979 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
980 }));
981 }
982
983 void resetPhiOptznState() {
984 Paths.clear();
985 VisitedPhis.clear();
986 }
987
988public:
989 ClobberWalker(const MemorySSA &MSSA, AliasAnalysis &AA, DominatorTree &DT,
990 WalkerCache &WC)
991 : MSSA(MSSA), AA(AA), DT(DT), WC(WC), UseCache(true) {}
992
993 void reset() { WalkTargetCache.clear(); }
994
995 /// Finds the nearest clobber for the given query, optimizing phis if
996 /// possible.
997 MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q,
998 bool UseWalkerCache = true) {
999 setUseCache(UseWalkerCache);
1000 Query = &Q;
1001
1002 MemoryAccess *Current = Start;
1003 // This walker pretends uses don't exist. If we're handed one, silently grab
1004 // its def. (This has the nice side-effect of ensuring we never cache uses)
1005 if (auto *MU = dyn_cast<MemoryUse>(Start))
1006 Current = MU->getDefiningAccess();
1007
1008 DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
1009 // Fast path for the overly-common case (no crazy phi optimization
1010 // necessary)
1011 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
George Burgess IV93ea19b2016-07-24 07:03:49 +00001012 MemoryAccess *Result;
George Burgess IV5f308972016-07-19 01:29:15 +00001013 if (WalkResult.IsKnownClobber) {
1014 cacheDefPath(FirstDesc, WalkResult.Result);
George Burgess IV93ea19b2016-07-24 07:03:49 +00001015 Result = WalkResult.Result;
1016 } else {
1017 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
1018 Current, Q.StartingLoc);
1019 verifyOptResult(OptRes);
1020 cacheOptResult(OptRes);
1021 resetPhiOptznState();
1022 Result = OptRes.PrimaryClobber.Clobber;
George Burgess IV5f308972016-07-19 01:29:15 +00001023 }
1024
George Burgess IV5f308972016-07-19 01:29:15 +00001025#ifdef EXPENSIVE_CHECKS
George Burgess IV93ea19b2016-07-24 07:03:49 +00001026 checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
George Burgess IV5f308972016-07-19 01:29:15 +00001027#endif
George Burgess IV93ea19b2016-07-24 07:03:49 +00001028 return Result;
George Burgess IV5f308972016-07-19 01:29:15 +00001029 }
Geoff Berrycdf53332016-08-08 17:52:01 +00001030
1031 void verify(const MemorySSA *MSSA) { assert(MSSA == &this->MSSA); }
George Burgess IV5f308972016-07-19 01:29:15 +00001032};
1033
1034struct RenamePassData {
1035 DomTreeNode *DTN;
1036 DomTreeNode::const_iterator ChildIt;
1037 MemoryAccess *IncomingVal;
1038
1039 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
1040 MemoryAccess *M)
1041 : DTN(D), ChildIt(It), IncomingVal(M) {}
1042 void swap(RenamePassData &RHS) {
1043 std::swap(DTN, RHS.DTN);
1044 std::swap(ChildIt, RHS.ChildIt);
1045 std::swap(IncomingVal, RHS.IncomingVal);
1046 }
1047};
1048} // anonymous namespace
1049
1050namespace llvm {
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001051/// \brief A MemorySSAWalker that does AA walks and caching of lookups to
1052/// disambiguate accesses.
1053///
1054/// FIXME: The current implementation of this can take quadratic space in rare
1055/// cases. This can be fixed, but it is something to note until it is fixed.
1056///
1057/// In order to trigger this behavior, you need to store to N distinct locations
1058/// (that AA can prove don't alias), perform M stores to other memory
1059/// locations that AA can prove don't alias any of the initial N locations, and
1060/// then load from all of the N locations. In this case, we insert M cache
1061/// entries for each of the N loads.
1062///
1063/// For example:
1064/// define i32 @foo() {
1065/// %a = alloca i32, align 4
1066/// %b = alloca i32, align 4
1067/// store i32 0, i32* %a, align 4
1068/// store i32 0, i32* %b, align 4
1069///
1070/// ; Insert M stores to other memory that doesn't alias %a or %b here
1071///
1072/// %c = load i32, i32* %a, align 4 ; Caches M entries in
1073/// ; CachedUpwardsClobberingAccess for the
1074/// ; MemoryLocation %a
1075/// %d = load i32, i32* %b, align 4 ; Caches M entries in
1076/// ; CachedUpwardsClobberingAccess for the
1077/// ; MemoryLocation %b
1078///
1079/// ; For completeness' sake, loading %a or %b again would not cache *another*
1080/// ; M entries.
1081/// %r = add i32 %c, %d
1082/// ret i32 %r
1083/// }
1084class MemorySSA::CachingWalker final : public MemorySSAWalker {
George Burgess IV5f308972016-07-19 01:29:15 +00001085 WalkerCache Cache;
1086 ClobberWalker Walker;
1087 bool AutoResetWalker;
1088
1089 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, UpwardsMemoryQuery &);
1090 void verifyRemoved(MemoryAccess *);
1091
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001092public:
1093 CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *);
1094 ~CachingWalker() override;
1095
George Burgess IV400ae402016-07-20 19:51:34 +00001096 using MemorySSAWalker::getClobberingMemoryAccess;
1097 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override;
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001098 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
1099 MemoryLocation &) override;
1100 void invalidateInfo(MemoryAccess *) override;
1101
George Burgess IV5f308972016-07-19 01:29:15 +00001102 /// Whether we call resetClobberWalker() after each time we *actually* walk to
1103 /// answer a clobber query.
1104 void setAutoResetWalker(bool AutoReset) { AutoResetWalker = AutoReset; }
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001105
George Burgess IV5f308972016-07-19 01:29:15 +00001106 /// Drop the walker's persistent data structures. At the moment, this means
1107 /// "drop the walker's cache of BasicBlocks ->
1108 /// earliest-MemoryAccess-we-can-optimize-to". This is necessary if we're
1109 /// going to have DT updates, if we remove MemoryAccesses, etc.
1110 void resetClobberWalker() { Walker.reset(); }
Geoff Berrycdf53332016-08-08 17:52:01 +00001111
1112 void verify(const MemorySSA *MSSA) override {
1113 MemorySSAWalker::verify(MSSA);
1114 Walker.verify(MSSA);
1115 }
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001116};
George Burgess IVe1100f52016-02-02 22:46:49 +00001117
George Burgess IVe1100f52016-02-02 22:46:49 +00001118/// \brief Rename a single basic block into MemorySSA form.
1119/// Uses the standard SSA renaming algorithm.
1120/// \returns The new incoming value.
1121MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB,
1122 MemoryAccess *IncomingVal) {
1123 auto It = PerBlockAccesses.find(BB);
1124 // Skip most processing if the list is empty.
1125 if (It != PerBlockAccesses.end()) {
Daniel Berlinada263d2016-06-20 20:21:33 +00001126 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001127 for (MemoryAccess &L : *Accesses) {
Daniel Berlin868381b2016-08-22 19:14:16 +00001128 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) {
1129 if (MUD->getDefiningAccess() == nullptr)
1130 MUD->setDefiningAccess(IncomingVal);
1131 if (isa<MemoryDef>(&L))
1132 IncomingVal = &L;
1133 } else {
George Burgess IVe1100f52016-02-02 22:46:49 +00001134 IncomingVal = &L;
George Burgess IVe1100f52016-02-02 22:46:49 +00001135 }
1136 }
1137 }
1138
1139 // Pass through values to our successors
1140 for (const BasicBlock *S : successors(BB)) {
1141 auto It = PerBlockAccesses.find(S);
1142 // Rename the phi nodes in our successor block
1143 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1144 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +00001145 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001146 auto *Phi = cast<MemoryPhi>(&Accesses->front());
George Burgess IVe1100f52016-02-02 22:46:49 +00001147 Phi->addIncoming(IncomingVal, BB);
1148 }
1149
1150 return IncomingVal;
1151}
1152
1153/// \brief This is the standard SSA renaming algorithm.
1154///
1155/// We walk the dominator tree in preorder, renaming accesses, and then filling
1156/// in phi nodes in our successors.
1157void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
1158 SmallPtrSet<BasicBlock *, 16> &Visited) {
1159 SmallVector<RenamePassData, 32> WorkStack;
1160 IncomingVal = renameBlock(Root->getBlock(), IncomingVal);
1161 WorkStack.push_back({Root, Root->begin(), IncomingVal});
1162 Visited.insert(Root->getBlock());
1163
1164 while (!WorkStack.empty()) {
1165 DomTreeNode *Node = WorkStack.back().DTN;
1166 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
1167 IncomingVal = WorkStack.back().IncomingVal;
1168
1169 if (ChildIt == Node->end()) {
1170 WorkStack.pop_back();
1171 } else {
1172 DomTreeNode *Child = *ChildIt;
1173 ++WorkStack.back().ChildIt;
1174 BasicBlock *BB = Child->getBlock();
1175 Visited.insert(BB);
1176 IncomingVal = renameBlock(BB, IncomingVal);
1177 WorkStack.push_back({Child, Child->begin(), IncomingVal});
1178 }
1179 }
1180}
1181
1182/// \brief Compute dominator levels, used by the phi insertion algorithm above.
1183void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) {
1184 for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode());
1185 DFI != DFE; ++DFI)
1186 DomLevels[*DFI] = DFI.getPathLength() - 1;
1187}
1188
George Burgess IVa362b092016-07-06 00:28:43 +00001189/// \brief This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +00001190/// unreachable blocks, and marking all other unreachable MemoryAccess's as
1191/// being uses of the live on entry definition.
1192void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
1193 assert(!DT->isReachableFromEntry(BB) &&
1194 "Reachable block found while handling unreachable blocks");
1195
Daniel Berlinfc7e6512016-07-06 05:32:05 +00001196 // Make sure phi nodes in our reachable successors end up with a
1197 // LiveOnEntryDef for our incoming edge, even though our block is forward
1198 // unreachable. We could just disconnect these blocks from the CFG fully,
1199 // but we do not right now.
1200 for (const BasicBlock *S : successors(BB)) {
1201 if (!DT->isReachableFromEntry(S))
1202 continue;
1203 auto It = PerBlockAccesses.find(S);
1204 // Rename the phi nodes in our successor block
1205 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1206 continue;
1207 AccessList *Accesses = It->second.get();
1208 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1209 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1210 }
1211
George Burgess IVe1100f52016-02-02 22:46:49 +00001212 auto It = PerBlockAccesses.find(BB);
1213 if (It == PerBlockAccesses.end())
1214 return;
1215
1216 auto &Accesses = It->second;
1217 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1218 auto Next = std::next(AI);
1219 // If we have a phi, just remove it. We are going to replace all
1220 // users with live on entry.
1221 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1222 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1223 else
1224 Accesses->erase(AI);
1225 AI = Next;
1226 }
1227}
1228
Geoff Berryb96d3b22016-06-01 21:30:40 +00001229MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
1230 : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
1231 NextID(0) {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001232 buildMemorySSA();
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)
Daniel Berlinada263d2016-06-20 20:21:33 +00001246 Res.first->second = make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001247 return Res.first->second.get();
1248}
1249
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001250/// This class is a batch walker of all MemoryUse's in the program, and points
1251/// their defining access at the thing that actually clobbers them. Because it
1252/// is a batch walker that touches everything, it does not operate like the
1253/// other walkers. This walker is basically performing a top-down SSA renaming
1254/// pass, where the version stack is used as the cache. This enables it to be
1255/// significantly more time and memory efficient than using the regular walker,
1256/// which is walking bottom-up.
1257class MemorySSA::OptimizeUses {
1258public:
1259 OptimizeUses(MemorySSA *MSSA, MemorySSAWalker *Walker, AliasAnalysis *AA,
1260 DominatorTree *DT)
1261 : MSSA(MSSA), Walker(Walker), AA(AA), DT(DT) {
1262 Walker = MSSA->getWalker();
1263 }
1264
1265 void optimizeUses();
1266
1267private:
1268 /// This represents where a given memorylocation is in the stack.
1269 struct MemlocStackInfo {
1270 // This essentially is keeping track of versions of the stack. Whenever
1271 // the stack changes due to pushes or pops, these versions increase.
1272 unsigned long StackEpoch;
1273 unsigned long PopEpoch;
1274 // This is the lower bound of places on the stack to check. It is equal to
1275 // the place the last stack walk ended.
1276 // Note: Correctness depends on this being initialized to 0, which densemap
1277 // does
1278 unsigned long LowerBound;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001279 const BasicBlock *LowerBoundBlock;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001280 // This is where the last walk for this memory location ended.
1281 unsigned long LastKill;
1282 bool LastKillValid;
1283 };
1284 void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1285 SmallVectorImpl<MemoryAccess *> &,
1286 DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
1287 MemorySSA *MSSA;
1288 MemorySSAWalker *Walker;
1289 AliasAnalysis *AA;
1290 DominatorTree *DT;
1291};
1292
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001293/// Optimize the uses in a given block This is basically the SSA renaming
1294/// algorithm, with one caveat: We are able to use a single stack for all
1295/// MemoryUses. This is because the set of *possible* reaching MemoryDefs is
1296/// the same for every MemoryUse. The *actual* clobbering MemoryDef is just
1297/// going to be some position in that stack of possible ones.
1298///
1299/// We track the stack positions that each MemoryLocation needs
1300/// to check, and last ended at. This is because we only want to check the
1301/// things that changed since last time. The same MemoryLocation should
1302/// get clobbered by the same store (getModRefInfo does not use invariantness or
1303/// things like this, and if they start, we can modify MemoryLocOrCall to
1304/// include relevant data)
1305void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1306 const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1307 SmallVectorImpl<MemoryAccess *> &VersionStack,
1308 DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
1309
1310 /// If no accesses, nothing to do.
1311 MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
1312 if (Accesses == nullptr)
1313 return;
1314
1315 // Pop everything that doesn't dominate the current block off the stack,
1316 // increment the PopEpoch to account for this.
1317 while (!VersionStack.empty()) {
1318 BasicBlock *BackBlock = VersionStack.back()->getBlock();
1319 if (DT->dominates(BackBlock, BB))
1320 break;
1321 while (VersionStack.back()->getBlock() == BackBlock)
1322 VersionStack.pop_back();
1323 ++PopEpoch;
1324 }
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001325 for (MemoryAccess &MA : *Accesses) {
1326 auto *MU = dyn_cast<MemoryUse>(&MA);
1327 if (!MU) {
1328 VersionStack.push_back(&MA);
1329 ++StackEpoch;
1330 continue;
1331 }
1332
George Burgess IV024f3d22016-08-03 19:57:02 +00001333 if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
1334 MU->setDefiningAccess(MSSA->getLiveOnEntryDef());
1335 continue;
1336 }
1337
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001338 MemoryLocOrCall UseMLOC(MU);
1339 auto &LocInfo = LocStackInfo[UseMLOC];
Daniel Berlin26fcea92016-08-02 20:02:21 +00001340 // If the pop epoch changed, it means we've removed stuff from top of
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001341 // stack due to changing blocks. We may have to reset the lower bound or
1342 // last kill info.
1343 if (LocInfo.PopEpoch != PopEpoch) {
1344 LocInfo.PopEpoch = PopEpoch;
1345 LocInfo.StackEpoch = StackEpoch;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001346 // If the lower bound was in something that no longer dominates us, we
1347 // have to reset it.
1348 // We can't simply track stack size, because the stack may have had
1349 // pushes/pops in the meantime.
1350 // XXX: This is non-optimal, but only is slower cases with heavily
1351 // branching dominator trees. To get the optimal number of queries would
1352 // be to make lowerbound and lastkill a per-loc stack, and pop it until
1353 // the top of that stack dominates us. This does not seem worth it ATM.
1354 // A much cheaper optimization would be to always explore the deepest
1355 // branch of the dominator tree first. This will guarantee this resets on
1356 // the smallest set of blocks.
1357 if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
Daniel Berlin1e98c042016-09-26 17:22:54 +00001358 !DT->dominates(LocInfo.LowerBoundBlock, BB)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001359 // Reset the lower bound of things to check.
1360 // TODO: Some day we should be able to reset to last kill, rather than
1361 // 0.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001362 LocInfo.LowerBound = 0;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001363 LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001364 LocInfo.LastKillValid = false;
1365 }
1366 } else if (LocInfo.StackEpoch != StackEpoch) {
1367 // If all that has changed is the StackEpoch, we only have to check the
1368 // new things on the stack, because we've checked everything before. In
1369 // this case, the lower bound of things to check remains the same.
1370 LocInfo.PopEpoch = PopEpoch;
1371 LocInfo.StackEpoch = StackEpoch;
1372 }
1373 if (!LocInfo.LastKillValid) {
1374 LocInfo.LastKill = VersionStack.size() - 1;
1375 LocInfo.LastKillValid = true;
1376 }
1377
1378 // At this point, we should have corrected last kill and LowerBound to be
1379 // in bounds.
1380 assert(LocInfo.LowerBound < VersionStack.size() &&
1381 "Lower bound out of range");
1382 assert(LocInfo.LastKill < VersionStack.size() &&
1383 "Last kill info out of range");
1384 // In any case, the new upper bound is the top of the stack.
1385 unsigned long UpperBound = VersionStack.size() - 1;
1386
1387 if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
Daniel Berlin26fcea92016-08-02 20:02:21 +00001388 DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
1389 << *(MU->getMemoryInst()) << ")"
1390 << " because there are " << UpperBound - LocInfo.LowerBound
1391 << " stores to disambiguate\n");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001392 // Because we did not walk, LastKill is no longer valid, as this may
1393 // have been a kill.
1394 LocInfo.LastKillValid = false;
1395 continue;
1396 }
1397 bool FoundClobberResult = false;
1398 while (UpperBound > LocInfo.LowerBound) {
1399 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1400 // For phis, use the walker, see where we ended up, go there
1401 Instruction *UseInst = MU->getMemoryInst();
1402 MemoryAccess *Result = Walker->getClobberingMemoryAccess(UseInst);
1403 // We are guaranteed to find it or something is wrong
1404 while (VersionStack[UpperBound] != Result) {
1405 assert(UpperBound != 0);
1406 --UpperBound;
1407 }
1408 FoundClobberResult = true;
1409 break;
1410 }
1411
1412 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
Daniel Berlindf101192016-08-03 00:01:46 +00001413 // If the lifetime of the pointer ends at this instruction, it's live on
1414 // entry.
1415 if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1416 // Reset UpperBound to liveOnEntryDef's place in the stack
1417 UpperBound = 0;
1418 FoundClobberResult = true;
1419 break;
1420 }
Daniel Berlindff31de2016-08-02 21:57:52 +00001421 if (instructionClobbersQuery(MD, MU, UseMLOC, *AA)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001422 FoundClobberResult = true;
1423 break;
1424 }
1425 --UpperBound;
1426 }
1427 // At the end of this loop, UpperBound is either a clobber, or lower bound
1428 // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1429 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
1430 MU->setDefiningAccess(VersionStack[UpperBound]);
1431 // We were last killed now by where we got to
1432 LocInfo.LastKill = UpperBound;
1433 } else {
1434 // Otherwise, we checked all the new ones, and now we know we can get to
1435 // LastKill.
1436 MU->setDefiningAccess(VersionStack[LocInfo.LastKill]);
1437 }
1438 LocInfo.LowerBound = VersionStack.size() - 1;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001439 LocInfo.LowerBoundBlock = BB;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001440 }
1441}
1442
1443/// Optimize uses to point to their actual clobbering definitions.
1444void MemorySSA::OptimizeUses::optimizeUses() {
1445
1446 // We perform a non-recursive top-down dominator tree walk
1447 struct StackInfo {
1448 const DomTreeNode *Node;
1449 DomTreeNode::const_iterator Iter;
1450 };
1451
1452 SmallVector<MemoryAccess *, 16> VersionStack;
1453 SmallVector<StackInfo, 16> DomTreeWorklist;
1454 DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001455 VersionStack.push_back(MSSA->getLiveOnEntryDef());
1456
1457 unsigned long StackEpoch = 1;
1458 unsigned long PopEpoch = 1;
Daniel Berlin7ac3d742016-08-05 22:09:14 +00001459 for (const auto *DomNode : depth_first(DT->getRootNode()))
1460 optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1461 LocStackInfo);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001462}
1463
Daniel Berlin3d512a22016-08-22 19:14:30 +00001464void MemorySSA::placePHINodes(
Daniel Berlin1e98c042016-09-26 17:22:54 +00001465 const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks) {
Daniel Berlin3d512a22016-08-22 19:14:30 +00001466 // Determine where our MemoryPhi's should go
1467 ForwardIDFCalculator IDFs(*DT);
1468 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001469 SmallVector<BasicBlock *, 32> IDFBlocks;
1470 IDFs.calculate(IDFBlocks);
1471
1472 // Now place MemoryPhi nodes.
1473 for (auto &BB : IDFBlocks) {
1474 // Insert phi node
1475 AccessList *Accesses = getOrCreateAccessList(BB);
1476 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
1477 ValueToMemoryAccess[BB] = Phi;
1478 // Phi's always are placed at the front of the block.
1479 Accesses->push_front(Phi);
1480 }
1481}
1482
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001483void MemorySSA::buildMemorySSA() {
George Burgess IVe1100f52016-02-02 22:46:49 +00001484 // We create an access to represent "live on entry", for things like
1485 // arguments or users of globals, where the memory they use is defined before
1486 // the beginning of the function. We do not actually insert it into the IR.
1487 // We do not define a live on exit for the immediate uses, and thus our
1488 // semantics do *not* imply that something with no immediate uses can simply
1489 // be removed.
1490 BasicBlock &StartingPoint = F.getEntryBlock();
1491 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
1492 &StartingPoint, NextID++);
1493
1494 // We maintain lists of memory accesses per-block, trading memory for time. We
1495 // could just look up the memory access for every possible instruction in the
1496 // stream.
1497 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001498 SmallPtrSet<BasicBlock *, 32> DefUseBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001499 // Go through each block, figure out where defs occur, and chain together all
1500 // the accesses.
1501 for (BasicBlock &B : F) {
Daniel Berlin7898ca62016-02-07 01:52:15 +00001502 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001503 AccessList *Accesses = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001504 for (Instruction &I : B) {
Peter Collingbourneffecb142016-05-26 01:19:17 +00001505 MemoryUseOrDef *MUD = createNewAccess(&I);
George Burgess IVb42b7622016-03-11 19:34:03 +00001506 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001507 continue;
George Burgess IV3887a412016-03-21 21:25:39 +00001508 InsertIntoDef |= isa<MemoryDef>(MUD);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001509
George Burgess IVe1100f52016-02-02 22:46:49 +00001510 if (!Accesses)
1511 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001512 Accesses->push_back(MUD);
George Burgess IVe1100f52016-02-02 22:46:49 +00001513 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001514 if (InsertIntoDef)
1515 DefiningBlocks.insert(&B);
George Burgess IV3887a412016-03-21 21:25:39 +00001516 if (Accesses)
Daniel Berlin1b51a292016-02-07 01:52:19 +00001517 DefUseBlocks.insert(&B);
1518 }
Daniel Berlin1e98c042016-09-26 17:22:54 +00001519 placePHINodes(DefiningBlocks);
George Burgess IVe1100f52016-02-02 22:46:49 +00001520
1521 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1522 // filled in with all blocks.
1523 SmallPtrSet<BasicBlock *, 16> Visited;
1524 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1525
George Burgess IV5f308972016-07-19 01:29:15 +00001526 CachingWalker *Walker = getWalkerImpl();
1527
1528 // We're doing a batch of updates; don't drop useful caches between them.
1529 Walker->setAutoResetWalker(false);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001530 OptimizeUses(this, Walker, AA, DT).optimizeUses();
George Burgess IV5f308972016-07-19 01:29:15 +00001531 Walker->setAutoResetWalker(true);
1532 Walker->resetClobberWalker();
1533
George Burgess IVe1100f52016-02-02 22:46:49 +00001534 // Mark the uses in unreachable blocks as live on entry, so that they go
1535 // somewhere.
1536 for (auto &BB : F)
1537 if (!Visited.count(&BB))
1538 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001539}
George Burgess IVe1100f52016-02-02 22:46:49 +00001540
George Burgess IV5f308972016-07-19 01:29:15 +00001541MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1542
1543MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001544 if (Walker)
1545 return Walker.get();
1546
1547 Walker = make_unique<CachingWalker>(this, AA, DT);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001548 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001549}
1550
Daniel Berlin14300262016-06-21 18:39:20 +00001551MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1552 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
1553 AccessList *Accesses = getOrCreateAccessList(BB);
1554 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001555 ValueToMemoryAccess[BB] = Phi;
Daniel Berlin14300262016-06-21 18:39:20 +00001556 // Phi's always are placed at the front of the block.
1557 Accesses->push_front(Phi);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001558 BlockNumberingValid.erase(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001559 return Phi;
1560}
1561
1562MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
1563 MemoryAccess *Definition) {
1564 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1565 MemoryUseOrDef *NewAccess = createNewAccess(I);
1566 assert(
1567 NewAccess != nullptr &&
1568 "Tried to create a memory access for a non-memory touching instruction");
1569 NewAccess->setDefiningAccess(Definition);
1570 return NewAccess;
1571}
1572
1573MemoryAccess *MemorySSA::createMemoryAccessInBB(Instruction *I,
1574 MemoryAccess *Definition,
1575 const BasicBlock *BB,
1576 InsertionPlace Point) {
1577 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1578 auto *Accesses = getOrCreateAccessList(BB);
1579 if (Point == Beginning) {
1580 // It goes after any phi nodes
David Majnemer42531262016-08-12 03:55:06 +00001581 auto AI = find_if(
1582 *Accesses, [](const MemoryAccess &MA) { return !isa<MemoryPhi>(MA); });
Daniel Berlin14300262016-06-21 18:39:20 +00001583
1584 Accesses->insert(AI, NewAccess);
1585 } else {
1586 Accesses->push_back(NewAccess);
1587 }
Daniel Berlin5c46b942016-07-19 22:49:43 +00001588 BlockNumberingValid.erase(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001589 return NewAccess;
1590}
1591MemoryAccess *MemorySSA::createMemoryAccessBefore(Instruction *I,
1592 MemoryAccess *Definition,
1593 MemoryAccess *InsertPt) {
1594 assert(I->getParent() == InsertPt->getBlock() &&
1595 "New and old access must be in the same block");
1596 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1597 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
1598 Accesses->insert(AccessList::iterator(InsertPt), NewAccess);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001599 BlockNumberingValid.erase(InsertPt->getBlock());
Daniel Berlin14300262016-06-21 18:39:20 +00001600 return NewAccess;
1601}
1602
1603MemoryAccess *MemorySSA::createMemoryAccessAfter(Instruction *I,
1604 MemoryAccess *Definition,
1605 MemoryAccess *InsertPt) {
1606 assert(I->getParent() == InsertPt->getBlock() &&
1607 "New and old access must be in the same block");
1608 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1609 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
1610 Accesses->insertAfter(AccessList::iterator(InsertPt), NewAccess);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001611 BlockNumberingValid.erase(InsertPt->getBlock());
Daniel Berlin14300262016-06-21 18:39:20 +00001612 return NewAccess;
1613}
1614
George Burgess IVe1100f52016-02-02 22:46:49 +00001615/// \brief Helper function to create new memory accesses
Peter Collingbourneffecb142016-05-26 01:19:17 +00001616MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001617 // The assume intrinsic has a control dependency which we model by claiming
1618 // that it writes arbitrarily. Ignore that fake memory dependency here.
1619 // FIXME: Replace this special casing with a more accurate modelling of
1620 // assume's control dependency.
1621 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1622 if (II->getIntrinsicID() == Intrinsic::assume)
1623 return nullptr;
1624
George Burgess IVe1100f52016-02-02 22:46:49 +00001625 // Find out what affect this instruction has on memory.
1626 ModRefInfo ModRef = AA->getModRefInfo(I);
1627 bool Def = bool(ModRef & MRI_Mod);
1628 bool Use = bool(ModRef & MRI_Ref);
1629
1630 // It's possible for an instruction to not modify memory at all. During
1631 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +00001632 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +00001633 return nullptr;
1634
1635 assert((Def || Use) &&
1636 "Trying to create a memory access with a non-memory instruction");
1637
George Burgess IVb42b7622016-03-11 19:34:03 +00001638 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001639 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +00001640 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +00001641 else
George Burgess IVb42b7622016-03-11 19:34:03 +00001642 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
Daniel Berlin5130cc82016-07-31 21:08:20 +00001643 ValueToMemoryAccess[I] = MUD;
George Burgess IVb42b7622016-03-11 19:34:03 +00001644 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001645}
1646
1647MemoryAccess *MemorySSA::findDominatingDef(BasicBlock *UseBlock,
1648 enum InsertionPlace Where) {
1649 // Handle the initial case
1650 if (Where == Beginning)
1651 // The only thing that could define us at the beginning is a phi node
1652 if (MemoryPhi *Phi = getMemoryAccess(UseBlock))
1653 return Phi;
1654
1655 DomTreeNode *CurrNode = DT->getNode(UseBlock);
1656 // Need to be defined by our dominator
1657 if (Where == Beginning)
1658 CurrNode = CurrNode->getIDom();
1659 Where = End;
1660 while (CurrNode) {
1661 auto It = PerBlockAccesses.find(CurrNode->getBlock());
1662 if (It != PerBlockAccesses.end()) {
1663 auto &Accesses = It->second;
David Majnemerd7708772016-06-24 04:05:21 +00001664 for (MemoryAccess &RA : reverse(*Accesses)) {
1665 if (isa<MemoryDef>(RA) || isa<MemoryPhi>(RA))
1666 return &RA;
George Burgess IVe1100f52016-02-02 22:46:49 +00001667 }
1668 }
1669 CurrNode = CurrNode->getIDom();
1670 }
1671 return LiveOnEntryDef.get();
1672}
1673
1674/// \brief Returns true if \p Replacer dominates \p Replacee .
1675bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1676 const MemoryAccess *Replacee) const {
1677 if (isa<MemoryUseOrDef>(Replacee))
1678 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1679 const auto *MP = cast<MemoryPhi>(Replacee);
1680 // For a phi node, the use occurs in the predecessor block of the phi node.
1681 // Since we may occur multiple times in the phi node, we have to check each
1682 // operand to ensure Replacer dominates each operand where Replacee occurs.
1683 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +00001684 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +00001685 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1686 return false;
1687 }
1688 return true;
1689}
1690
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001691/// \brief If all arguments of a MemoryPHI are defined by the same incoming
1692/// argument, return that argument.
1693static MemoryAccess *onlySingleValue(MemoryPhi *MP) {
1694 MemoryAccess *MA = nullptr;
1695
1696 for (auto &Arg : MP->operands()) {
1697 if (!MA)
1698 MA = cast<MemoryAccess>(Arg);
1699 else if (MA != Arg)
1700 return nullptr;
1701 }
1702 return MA;
1703}
1704
1705/// \brief Properly remove \p MA from all of MemorySSA's lookup tables.
1706///
1707/// Because of the way the intrusive list and use lists work, it is important to
1708/// do removal in the right order.
1709void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1710 assert(MA->use_empty() &&
1711 "Trying to remove memory access that still has uses");
Daniel Berlin5c46b942016-07-19 22:49:43 +00001712 BlockNumbering.erase(MA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001713 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
1714 MUD->setDefiningAccess(nullptr);
1715 // Invalidate our walker's cache if necessary
1716 if (!isa<MemoryUse>(MA))
1717 Walker->invalidateInfo(MA);
1718 // The call below to erase will destroy MA, so we can't change the order we
1719 // are doing things here
1720 Value *MemoryInst;
1721 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1722 MemoryInst = MUD->getMemoryInst();
1723 } else {
1724 MemoryInst = MA->getBlock();
1725 }
Daniel Berlin5130cc82016-07-31 21:08:20 +00001726 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1727 if (VMA->second == MA)
1728 ValueToMemoryAccess.erase(VMA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001729
George Burgess IVe0e6e482016-03-02 02:35:04 +00001730 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
Daniel Berlinada263d2016-06-20 20:21:33 +00001731 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001732 Accesses->erase(MA);
George Burgess IVe0e6e482016-03-02 02:35:04 +00001733 if (Accesses->empty())
1734 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001735}
1736
1737void MemorySSA::removeMemoryAccess(MemoryAccess *MA) {
1738 assert(!isLiveOnEntryDef(MA) && "Trying to remove the live on entry def");
1739 // We can only delete phi nodes if they have no uses, or we can replace all
1740 // uses with a single definition.
1741 MemoryAccess *NewDefTarget = nullptr;
1742 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) {
1743 // Note that it is sufficient to know that all edges of the phi node have
1744 // the same argument. If they do, by the definition of dominance frontiers
1745 // (which we used to place this phi), that argument must dominate this phi,
1746 // and thus, must dominate the phi's uses, and so we will not hit the assert
1747 // below.
1748 NewDefTarget = onlySingleValue(MP);
1749 assert((NewDefTarget || MP->use_empty()) &&
1750 "We can't delete this memory phi");
1751 } else {
1752 NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
1753 }
1754
1755 // Re-point the uses at our defining access
1756 if (!MA->use_empty())
1757 MA->replaceAllUsesWith(NewDefTarget);
1758
1759 // The call below to erase will destroy MA, so we can't change the order we
1760 // are doing things here
1761 removeFromLookups(MA);
1762}
1763
George Burgess IVe1100f52016-02-02 22:46:49 +00001764void MemorySSA::print(raw_ostream &OS) const {
1765 MemorySSAAnnotatedWriter Writer(this);
1766 F.print(OS, &Writer);
1767}
1768
1769void MemorySSA::dump() const {
1770 MemorySSAAnnotatedWriter Writer(this);
1771 F.print(dbgs(), &Writer);
1772}
1773
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001774void MemorySSA::verifyMemorySSA() const {
1775 verifyDefUses(F);
1776 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001777 verifyOrdering(F);
Geoff Berrycdf53332016-08-08 17:52:01 +00001778 Walker->verify(this);
Daniel Berlin14300262016-06-21 18:39:20 +00001779}
1780
1781/// \brief Verify that the order and existence of MemoryAccesses matches the
1782/// order and existence of memory affecting instructions.
1783void MemorySSA::verifyOrdering(Function &F) const {
1784 // Walk all the blocks, comparing what the lookups think and what the access
1785 // lists think, as well as the order in the blocks vs the order in the access
1786 // lists.
1787 SmallVector<MemoryAccess *, 32> ActualAccesses;
1788 for (BasicBlock &B : F) {
1789 const AccessList *AL = getBlockAccesses(&B);
1790 MemoryAccess *Phi = getMemoryAccess(&B);
1791 if (Phi)
1792 ActualAccesses.push_back(Phi);
1793 for (Instruction &I : B) {
1794 MemoryAccess *MA = getMemoryAccess(&I);
1795 assert((!MA || AL) && "We have memory affecting instructions "
1796 "in this block but they are not in the "
1797 "access list");
1798 if (MA)
1799 ActualAccesses.push_back(MA);
1800 }
1801 // Either we hit the assert, really have no accesses, or we have both
1802 // accesses and an access list
1803 if (!AL)
1804 continue;
1805 assert(AL->size() == ActualAccesses.size() &&
1806 "We don't have the same number of accesses in the block as on the "
1807 "access list");
1808 auto ALI = AL->begin();
1809 auto AAI = ActualAccesses.begin();
1810 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1811 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1812 ++ALI;
1813 ++AAI;
1814 }
1815 ActualAccesses.clear();
1816 }
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001817}
1818
George Burgess IVe1100f52016-02-02 22:46:49 +00001819/// \brief Verify the domination properties of MemorySSA by checking that each
1820/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001821void MemorySSA::verifyDomination(Function &F) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001822#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001823 for (BasicBlock &B : F) {
1824 // Phi nodes are attached to basic blocks
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001825 if (MemoryPhi *MP = getMemoryAccess(&B))
1826 for (const Use &U : MP->uses())
1827 assert(dominates(MP, U) && "Memory PHI does not dominate it's uses");
Daniel Berlin7af95872016-08-05 21:47:20 +00001828
George Burgess IVe1100f52016-02-02 22:46:49 +00001829 for (Instruction &I : B) {
1830 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
1831 if (!MD)
1832 continue;
1833
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001834 for (const Use &U : MD->uses())
1835 assert(dominates(MD, U) && "Memory Def does not dominate it's uses");
George Burgess IVe1100f52016-02-02 22:46:49 +00001836 }
1837 }
Daniel Berlin7af95872016-08-05 21:47:20 +00001838#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001839}
1840
1841/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
1842/// appears in the use list of \p Def.
Daniel Berlin7af95872016-08-05 21:47:20 +00001843
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001844void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001845#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001846 // The live on entry use may cause us to get a NULL def here
Daniel Berlin7af95872016-08-05 21:47:20 +00001847 if (!Def)
1848 assert(isLiveOnEntryDef(Use) &&
1849 "Null def but use not point to live on entry def");
1850 else
Daniel Berlinda2f38e2016-08-11 21:26:50 +00001851 assert(is_contained(Def->users(), Use) &&
Daniel Berlin7af95872016-08-05 21:47:20 +00001852 "Did not find use in def's use list");
1853#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001854}
1855
1856/// \brief Verify the immediate use information, by walking all the memory
1857/// accesses and verifying that, for each use, it appears in the
1858/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001859void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001860 for (BasicBlock &B : F) {
1861 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00001862 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00001863 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
1864 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00001865 "Incomplete MemoryPhi Node");
George Burgess IVe1100f52016-02-02 22:46:49 +00001866 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1867 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Daniel Berlin14300262016-06-21 18:39:20 +00001868 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001869
1870 for (Instruction &I : B) {
1871 if (MemoryAccess *MA = getMemoryAccess(&I)) {
1872 assert(isa<MemoryUseOrDef>(MA) &&
1873 "Found a phi node not attached to a bb");
1874 verifyUseInDefs(cast<MemoryUseOrDef>(MA)->getDefiningAccess(), MA);
1875 }
1876 }
1877 }
1878}
1879
1880MemoryAccess *MemorySSA::getMemoryAccess(const Value *I) const {
Daniel Berlinf6c9ae92016-02-10 17:41:25 +00001881 return ValueToMemoryAccess.lookup(I);
George Burgess IVe1100f52016-02-02 22:46:49 +00001882}
1883
1884MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
1885 return cast_or_null<MemoryPhi>(getMemoryAccess((const Value *)BB));
1886}
1887
Daniel Berlin5c46b942016-07-19 22:49:43 +00001888/// Perform a local numbering on blocks so that instruction ordering can be
1889/// determined in constant time.
1890/// TODO: We currently just number in order. If we numbered by N, we could
1891/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
1892/// log2(N) sequences of mixed before and after) without needing to invalidate
1893/// the numbering.
1894void MemorySSA::renumberBlock(const BasicBlock *B) const {
1895 // The pre-increment ensures the numbers really start at 1.
1896 unsigned long CurrentNumber = 0;
1897 const AccessList *AL = getBlockAccesses(B);
1898 assert(AL != nullptr && "Asking to renumber an empty block");
1899 for (const auto &I : *AL)
1900 BlockNumbering[&I] = ++CurrentNumber;
1901 BlockNumberingValid.insert(B);
1902}
1903
George Burgess IVe1100f52016-02-02 22:46:49 +00001904/// \brief Determine, for two memory accesses in the same block,
1905/// whether \p Dominator dominates \p Dominatee.
1906/// \returns True if \p Dominator dominates \p Dominatee.
1907bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
1908 const MemoryAccess *Dominatee) const {
Sebastian Pope1f60b12016-06-10 21:36:41 +00001909
Daniel Berlin5c46b942016-07-19 22:49:43 +00001910 const BasicBlock *DominatorBlock = Dominator->getBlock();
Daniel Berlin5c46b942016-07-19 22:49:43 +00001911
Daniel Berlin19860302016-07-19 23:08:08 +00001912 assert((DominatorBlock == Dominatee->getBlock()) &&
Daniel Berlin5c46b942016-07-19 22:49:43 +00001913 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00001914 // A node dominates itself.
1915 if (Dominatee == Dominator)
1916 return true;
1917
1918 // When Dominatee is defined on function entry, it is not dominated by another
1919 // memory access.
1920 if (isLiveOnEntryDef(Dominatee))
1921 return false;
1922
1923 // When Dominator is defined on function entry, it dominates the other memory
1924 // access.
1925 if (isLiveOnEntryDef(Dominator))
1926 return true;
1927
Daniel Berlin5c46b942016-07-19 22:49:43 +00001928 if (!BlockNumberingValid.count(DominatorBlock))
1929 renumberBlock(DominatorBlock);
George Burgess IVe1100f52016-02-02 22:46:49 +00001930
Daniel Berlin5c46b942016-07-19 22:49:43 +00001931 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
1932 // All numbers start with 1
1933 assert(DominatorNum != 0 && "Block was not numbered properly");
1934 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
1935 assert(DominateeNum != 0 && "Block was not numbered properly");
1936 return DominatorNum < DominateeNum;
George Burgess IVe1100f52016-02-02 22:46:49 +00001937}
1938
George Burgess IV5f308972016-07-19 01:29:15 +00001939bool MemorySSA::dominates(const MemoryAccess *Dominator,
1940 const MemoryAccess *Dominatee) const {
1941 if (Dominator == Dominatee)
1942 return true;
1943
1944 if (isLiveOnEntryDef(Dominatee))
1945 return false;
1946
1947 if (Dominator->getBlock() != Dominatee->getBlock())
1948 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
1949 return locallyDominates(Dominator, Dominatee);
1950}
1951
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001952bool MemorySSA::dominates(const MemoryAccess *Dominator,
1953 const Use &Dominatee) const {
1954 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
1955 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
1956 // The def must dominate the incoming block of the phi.
1957 if (UseBB != Dominator->getBlock())
1958 return DT->dominates(Dominator->getBlock(), UseBB);
1959 // If the UseBB and the DefBB are the same, compare locally.
1960 return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
1961 }
1962 // If it's not a PHI node use, the normal dominates can already handle it.
1963 return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
1964}
1965
George Burgess IVe1100f52016-02-02 22:46:49 +00001966const static char LiveOnEntryStr[] = "liveOnEntry";
1967
1968void MemoryDef::print(raw_ostream &OS) const {
1969 MemoryAccess *UO = getDefiningAccess();
1970
1971 OS << getID() << " = MemoryDef(";
1972 if (UO && UO->getID())
1973 OS << UO->getID();
1974 else
1975 OS << LiveOnEntryStr;
1976 OS << ')';
1977}
1978
1979void MemoryPhi::print(raw_ostream &OS) const {
1980 bool First = true;
1981 OS << getID() << " = MemoryPhi(";
1982 for (const auto &Op : operands()) {
1983 BasicBlock *BB = getIncomingBlock(Op);
1984 MemoryAccess *MA = cast<MemoryAccess>(Op);
1985 if (!First)
1986 OS << ',';
1987 else
1988 First = false;
1989
1990 OS << '{';
1991 if (BB->hasName())
1992 OS << BB->getName();
1993 else
1994 BB->printAsOperand(OS, false);
1995 OS << ',';
1996 if (unsigned ID = MA->getID())
1997 OS << ID;
1998 else
1999 OS << LiveOnEntryStr;
2000 OS << '}';
2001 }
2002 OS << ')';
2003}
2004
2005MemoryAccess::~MemoryAccess() {}
2006
2007void MemoryUse::print(raw_ostream &OS) const {
2008 MemoryAccess *UO = getDefiningAccess();
2009 OS << "MemoryUse(";
2010 if (UO && UO->getID())
2011 OS << UO->getID();
2012 else
2013 OS << LiveOnEntryStr;
2014 OS << ')';
2015}
2016
2017void MemoryAccess::dump() const {
2018 print(dbgs());
2019 dbgs() << "\n";
2020}
2021
Chad Rosier232e29e2016-07-06 21:20:47 +00002022char MemorySSAPrinterLegacyPass::ID = 0;
2023
2024MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
2025 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
2026}
2027
2028void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
2029 AU.setPreservesAll();
2030 AU.addRequired<MemorySSAWrapperPass>();
2031 AU.addPreserved<MemorySSAWrapperPass>();
2032}
2033
2034bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
2035 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2036 MSSA.print(dbgs());
2037 if (VerifyMemorySSA)
2038 MSSA.verifyMemorySSA();
2039 return false;
2040}
2041
Geoff Berryb96d3b22016-06-01 21:30:40 +00002042char MemorySSAAnalysis::PassID;
George Burgess IVe1100f52016-02-02 22:46:49 +00002043
Daniel Berlin1e98c042016-09-26 17:22:54 +00002044MemorySSAAnalysis::Result MemorySSAAnalysis::run(Function &F,
2045 FunctionAnalysisManager &AM) {
Geoff Berryb96d3b22016-06-01 21:30:40 +00002046 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2047 auto &AA = AM.getResult<AAManager>(F);
Geoff Berry290a13e2016-08-08 18:27:22 +00002048 return MemorySSAAnalysis::Result(make_unique<MemorySSA>(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002049}
2050
Geoff Berryb96d3b22016-06-01 21:30:40 +00002051PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
2052 FunctionAnalysisManager &AM) {
2053 OS << "MemorySSA for function: " << F.getName() << "\n";
Geoff Berry290a13e2016-08-08 18:27:22 +00002054 AM.getResult<MemorySSAAnalysis>(F).getMSSA().print(OS);
Geoff Berryb96d3b22016-06-01 21:30:40 +00002055
2056 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00002057}
2058
Geoff Berryb96d3b22016-06-01 21:30:40 +00002059PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
2060 FunctionAnalysisManager &AM) {
Geoff Berry290a13e2016-08-08 18:27:22 +00002061 AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002062
2063 return PreservedAnalyses::all();
2064}
2065
2066char MemorySSAWrapperPass::ID = 0;
2067
2068MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
2069 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
2070}
2071
2072void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
2073
2074void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002075 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002076 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
2077 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00002078}
2079
Geoff Berryb96d3b22016-06-01 21:30:40 +00002080bool MemorySSAWrapperPass::runOnFunction(Function &F) {
2081 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2082 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2083 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002084 return false;
2085}
2086
Geoff Berryb96d3b22016-06-01 21:30:40 +00002087void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00002088
Geoff Berryb96d3b22016-06-01 21:30:40 +00002089void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002090 MSSA->print(OS);
2091}
2092
George Burgess IVe1100f52016-02-02 22:46:49 +00002093MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
2094
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002095MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A,
2096 DominatorTree *D)
Daniel Berlin5c46b942016-07-19 22:49:43 +00002097 : MemorySSAWalker(M), Walker(*M, *A, *D, Cache), AutoResetWalker(true) {}
George Burgess IVe1100f52016-02-02 22:46:49 +00002098
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002099MemorySSA::CachingWalker::~CachingWalker() {}
George Burgess IVe1100f52016-02-02 22:46:49 +00002100
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002101void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) {
Daniel Berlin83fc77b2016-03-01 18:46:54 +00002102 // TODO: We can do much better cache invalidation with differently stored
2103 // caches. For now, for MemoryUses, we simply remove them
2104 // from the cache, and kill the entire call/non-call cache for everything
2105 // else. The problem is for phis or defs, currently we'd need to follow use
2106 // chains down and invalidate anything below us in the chain that currently
2107 // terminates at this access.
2108
2109 // See if this is a MemoryUse, if so, just remove the cached info. MemoryUse
2110 // is by definition never a barrier, so nothing in the cache could point to
2111 // this use. In that case, we only need invalidate the info for the use
2112 // itself.
2113
2114 if (MemoryUse *MU = dyn_cast<MemoryUse>(MA)) {
George Burgess IV5f308972016-07-19 01:29:15 +00002115 UpwardsMemoryQuery Q(MU->getMemoryInst(), MU);
2116 Cache.remove(MU, Q.StartingLoc, Q.IsCall);
Geoff Berry9fe26e62016-04-22 14:44:10 +00002117 } else {
2118 // If it is not a use, the best we can do right now is destroy the cache.
George Burgess IV5f308972016-07-19 01:29:15 +00002119 Cache.clear();
Geoff Berry9fe26e62016-04-22 14:44:10 +00002120 }
2121
Filipe Cabecinhas0da99372016-04-29 15:22:48 +00002122#ifdef EXPENSIVE_CHECKS
Geoff Berry9fe26e62016-04-22 14:44:10 +00002123 verifyRemoved(MA);
2124#endif
Daniel Berlin83fc77b2016-03-01 18:46:54 +00002125}
2126
George Burgess IVe1100f52016-02-02 22:46:49 +00002127/// \brief Walk the use-def chains starting at \p MA and find
2128/// the MemoryAccess that actually clobbers Loc.
2129///
2130/// \returns our clobbering memory access
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002131MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
2132 MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +00002133 MemoryAccess *New = Walker.findClobber(StartingAccess, Q);
2134#ifdef EXPENSIVE_CHECKS
2135 MemoryAccess *NewNoCache =
2136 Walker.findClobber(StartingAccess, Q, /*UseWalkerCache=*/false);
2137 assert(NewNoCache == New && "Cache made us hand back a different result?");
2138#endif
2139 if (AutoResetWalker)
2140 resetClobberWalker();
2141 return New;
George Burgess IVe1100f52016-02-02 22:46:49 +00002142}
2143
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002144MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
2145 MemoryAccess *StartingAccess, MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002146 if (isa<MemoryPhi>(StartingAccess))
2147 return StartingAccess;
2148
2149 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
2150 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
2151 return StartingUseOrDef;
2152
2153 Instruction *I = StartingUseOrDef->getMemoryInst();
2154
2155 // Conservatively, fences are always clobbers, so don't perform the walk if we
2156 // hit a fence.
David Majnemera940f362016-07-15 17:19:24 +00002157 if (!ImmutableCallSite(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002158 return StartingUseOrDef;
2159
2160 UpwardsMemoryQuery Q;
2161 Q.OriginalAccess = StartingUseOrDef;
2162 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00002163 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00002164 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00002165
George Burgess IV5f308972016-07-19 01:29:15 +00002166 if (auto *CacheResult = Cache.lookup(StartingUseOrDef, Loc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00002167 return CacheResult;
2168
2169 // Unlike the other function, do not walk to the def of a def, because we are
2170 // handed something we already believe is the clobbering access.
2171 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
2172 ? StartingUseOrDef->getDefiningAccess()
2173 : StartingUseOrDef;
2174
2175 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002176 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2177 DEBUG(dbgs() << *StartingUseOrDef << "\n");
2178 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2179 DEBUG(dbgs() << *Clobber << "\n");
2180 return Clobber;
2181}
2182
2183MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002184MemorySSA::CachingWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
2185 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2186 // If this is a MemoryPhi, we can't do anything.
2187 if (!StartingAccess)
2188 return MA;
George Burgess IVe1100f52016-02-02 22:46:49 +00002189
George Burgess IV400ae402016-07-20 19:51:34 +00002190 const Instruction *I = StartingAccess->getMemoryInst();
George Burgess IV5f308972016-07-19 01:29:15 +00002191 UpwardsMemoryQuery Q(I, StartingAccess);
David Majnemera940f362016-07-15 17:19:24 +00002192 // We can't sanely do anything with a fences, they conservatively
George Burgess IVe1100f52016-02-02 22:46:49 +00002193 // clobber all memory, and have no locations to get pointers from to
David Majnemera940f362016-07-15 17:19:24 +00002194 // try to disambiguate.
George Burgess IV5f308972016-07-19 01:29:15 +00002195 if (!Q.IsCall && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002196 return StartingAccess;
2197
George Burgess IV5f308972016-07-19 01:29:15 +00002198 if (auto *CacheResult = Cache.lookup(StartingAccess, Q.StartingLoc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00002199 return CacheResult;
2200
George Burgess IV024f3d22016-08-03 19:57:02 +00002201 if (isUseTriviallyOptimizableToLiveOnEntry(*MSSA->AA, I)) {
2202 MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
2203 Cache.insert(StartingAccess, LiveOnEntry, Q.StartingLoc, Q.IsCall);
2204 return LiveOnEntry;
2205 }
2206
George Burgess IVe1100f52016-02-02 22:46:49 +00002207 // Start with the thing we already think clobbers this location
2208 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2209
2210 // At this point, DefiningAccess may be the live on entry def.
2211 // If it is, we will not get a better result.
2212 if (MSSA->isLiveOnEntryDef(DefiningAccess))
2213 return DefiningAccess;
2214
2215 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002216 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2217 DEBUG(dbgs() << *DefiningAccess << "\n");
2218 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2219 DEBUG(dbgs() << *Result << "\n");
2220
2221 return Result;
2222}
2223
Geoff Berry9fe26e62016-04-22 14:44:10 +00002224// Verify that MA doesn't exist in any of the caches.
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002225void MemorySSA::CachingWalker::verifyRemoved(MemoryAccess *MA) {
George Burgess IV5f308972016-07-19 01:29:15 +00002226 assert(!Cache.contains(MA) && "Found removed MemoryAccess in cache.");
Geoff Berry9fe26e62016-04-22 14:44:10 +00002227}
2228
George Burgess IVe1100f52016-02-02 22:46:49 +00002229MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002230DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002231 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2232 return Use->getDefiningAccess();
2233 return MA;
2234}
2235
2236MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
2237 MemoryAccess *StartingAccess, MemoryLocation &) {
2238 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2239 return Use->getDefiningAccess();
2240 return StartingAccess;
2241}
George Burgess IV5f308972016-07-19 01:29:15 +00002242} // namespace llvm