blob: f90ab6eac2b5f5f942a021ce13e5464bc40341cd [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};
172}
George Burgess IV024f3d22016-08-03 19:57:02 +0000173
Daniel Berlindff31de2016-08-02 21:57:52 +0000174namespace {
George Burgess IV5f308972016-07-19 01:29:15 +0000175struct UpwardsMemoryQuery {
176 // True if our original query started off as a call
177 bool IsCall;
178 // The pointer location we started the query with. This will be empty if
179 // IsCall is true.
180 MemoryLocation StartingLoc;
181 // This is the instruction we were querying about.
182 const Instruction *Inst;
183 // The MemoryAccess we actually got called with, used to test local domination
184 const MemoryAccess *OriginalAccess;
185
186 UpwardsMemoryQuery()
187 : IsCall(false), Inst(nullptr), OriginalAccess(nullptr) {}
188
189 UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
190 : IsCall(ImmutableCallSite(Inst)), Inst(Inst), OriginalAccess(Access) {
191 if (!IsCall)
192 StartingLoc = MemoryLocation::get(Inst);
193 }
194};
195
Daniel Berlindf101192016-08-03 00:01:46 +0000196static bool lifetimeEndsAt(MemoryDef *MD, const MemoryLocation &Loc,
197 AliasAnalysis &AA) {
198 Instruction *Inst = MD->getMemoryInst();
199 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
200 switch (II->getIntrinsicID()) {
201 case Intrinsic::lifetime_start:
202 case Intrinsic::lifetime_end:
203 return AA.isMustAlias(MemoryLocation(II->getArgOperand(1)), Loc);
204 default:
205 return false;
206 }
207 }
208 return false;
209}
210
George Burgess IV82e355c2016-08-03 19:39:54 +0000211enum class Reorderability {
212 Always,
213 IfNoAlias,
214 Never
215};
216
217/// This does one-way checks to see if Use could theoretically be hoisted above
218/// MayClobber. This will not check the other way around.
219///
220/// This assumes that, for the purposes of MemorySSA, Use comes directly after
221/// MayClobber, with no potentially clobbering operations in between them.
222/// (Where potentially clobbering ops are memory barriers, aliased stores, etc.)
223static Reorderability getLoadReorderability(const LoadInst *Use,
224 const LoadInst *MayClobber) {
225 bool VolatileUse = Use->isVolatile();
226 bool VolatileClobber = MayClobber->isVolatile();
227 // Volatile operations may never be reordered with other volatile operations.
228 if (VolatileUse && VolatileClobber)
229 return Reorderability::Never;
230
231 // The lang ref allows reordering of volatile and non-volatile operations.
232 // Whether an aliasing nonvolatile load and volatile load can be reordered,
233 // though, is ambiguous. Because it may not be best to exploit this ambiguity,
234 // we only allow volatile/non-volatile reordering if the volatile and
235 // non-volatile operations don't alias.
236 Reorderability Result = VolatileUse || VolatileClobber
237 ? Reorderability::IfNoAlias
238 : Reorderability::Always;
239
240 // If a load is seq_cst, it cannot be moved above other loads. If its ordering
241 // is weaker, it can be moved above other loads. We just need to be sure that
242 // MayClobber isn't an acquire load, because loads can't be moved above
243 // acquire loads.
244 //
245 // Note that this explicitly *does* allow the free reordering of monotonic (or
246 // weaker) loads of the same address.
247 bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent;
248 bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(),
249 AtomicOrdering::Acquire);
250 if (SeqCstUse || MayClobberIsAcquire)
251 return Reorderability::Never;
252 return Result;
253}
254
George Burgess IV024f3d22016-08-03 19:57:02 +0000255static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysis &AA,
256 const Instruction *I) {
257 // If the memory can't be changed, then loads of the memory can't be
258 // clobbered.
259 //
260 // FIXME: We should handle invariant groups, as well. It's a bit harder,
261 // because we need to pay close attention to invariant group barriers.
262 return isa<LoadInst>(I) && (I->getMetadata(LLVMContext::MD_invariant_load) ||
263 AA.pointsToConstantMemory(I));
264}
265
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000266static bool instructionClobbersQuery(MemoryDef *MD,
267 const MemoryLocation &UseLoc,
268 const Instruction *UseInst,
George Burgess IV5f308972016-07-19 01:29:15 +0000269 AliasAnalysis &AA) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000270 Instruction *DefInst = MD->getMemoryInst();
271 assert(DefInst && "Defining instruction not actually an instruction");
George Burgess IV5f308972016-07-19 01:29:15 +0000272
Daniel Berlindf101192016-08-03 00:01:46 +0000273 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
274 // These intrinsics will show up as affecting memory, but they are just
275 // markers.
276 switch (II->getIntrinsicID()) {
277 case Intrinsic::lifetime_start:
278 case Intrinsic::lifetime_end:
279 case Intrinsic::invariant_start:
280 case Intrinsic::invariant_end:
281 case Intrinsic::assume:
282 return false;
283 default:
284 break;
285 }
286 }
287
Daniel Berlindff31de2016-08-02 21:57:52 +0000288 ImmutableCallSite UseCS(UseInst);
289 if (UseCS) {
290 ModRefInfo I = AA.getModRefInfo(DefInst, UseCS);
291 return I != MRI_NoModRef;
292 }
George Burgess IV82e355c2016-08-03 19:39:54 +0000293
294 if (auto *DefLoad = dyn_cast<LoadInst>(DefInst)) {
295 if (auto *UseLoad = dyn_cast<LoadInst>(UseInst)) {
296 switch (getLoadReorderability(UseLoad, DefLoad)) {
297 case Reorderability::Always:
298 return false;
299 case Reorderability::Never:
300 return true;
301 case Reorderability::IfNoAlias:
302 return !AA.isNoAlias(UseLoc, MemoryLocation::get(DefLoad));
303 }
304 }
305 }
306
Daniel Berlindff31de2016-08-02 21:57:52 +0000307 return AA.getModRefInfo(DefInst, UseLoc) & MRI_Mod;
308}
309
310static bool instructionClobbersQuery(MemoryDef *MD, MemoryUse *MU,
311 const MemoryLocOrCall &UseMLOC,
312 AliasAnalysis &AA) {
313 // FIXME: This is a temporary hack to allow a single instructionClobbersQuery
314 // to exist while MemoryLocOrCall is pushed through places.
315 if (UseMLOC.IsCall)
316 return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(),
317 AA);
318 return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(),
319 AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000320}
321
322/// Cache for our caching MemorySSA walker.
323class WalkerCache {
324 DenseMap<ConstMemoryAccessPair, MemoryAccess *> Accesses;
325 DenseMap<const MemoryAccess *, MemoryAccess *> Calls;
326
327public:
328 MemoryAccess *lookup(const MemoryAccess *MA, const MemoryLocation &Loc,
329 bool IsCall) const {
330 ++NumClobberCacheLookups;
331 MemoryAccess *R = IsCall ? Calls.lookup(MA) : Accesses.lookup({MA, Loc});
332 if (R)
333 ++NumClobberCacheHits;
334 return R;
335 }
336
337 bool insert(const MemoryAccess *MA, MemoryAccess *To,
338 const MemoryLocation &Loc, bool IsCall) {
339 // This is fine for Phis, since there are times where we can't optimize
340 // them. Making a def its own clobber is never correct, though.
341 assert((MA != To || isa<MemoryPhi>(MA)) &&
342 "Something can't clobber itself!");
343
344 ++NumClobberCacheInserts;
345 bool Inserted;
346 if (IsCall)
347 Inserted = Calls.insert({MA, To}).second;
348 else
349 Inserted = Accesses.insert({{MA, Loc}, To}).second;
350
351 return Inserted;
352 }
353
354 bool remove(const MemoryAccess *MA, const MemoryLocation &Loc, bool IsCall) {
355 return IsCall ? Calls.erase(MA) : Accesses.erase({MA, Loc});
356 }
357
358 void clear() {
359 Accesses.clear();
360 Calls.clear();
361 }
362
363 bool contains(const MemoryAccess *MA) const {
364 for (auto &P : Accesses)
365 if (P.first.first == MA || P.second == MA)
366 return true;
367 for (auto &P : Calls)
368 if (P.first == MA || P.second == MA)
369 return true;
370 return false;
371 }
372};
373
374/// Walks the defining uses of MemoryDefs. Stops after we hit something that has
375/// no defining use (e.g. a MemoryPhi or liveOnEntry). Note that, when comparing
376/// against a null def_chain_iterator, this will compare equal only after
377/// walking said Phi/liveOnEntry.
378struct def_chain_iterator
379 : public iterator_facade_base<def_chain_iterator, std::forward_iterator_tag,
380 MemoryAccess *> {
381 def_chain_iterator() : MA(nullptr) {}
382 def_chain_iterator(MemoryAccess *MA) : MA(MA) {}
383
384 MemoryAccess *operator*() const { return MA; }
385
386 def_chain_iterator &operator++() {
387 // N.B. liveOnEntry has a null defining access.
388 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
389 MA = MUD->getDefiningAccess();
390 else
391 MA = nullptr;
392 return *this;
393 }
394
395 bool operator==(const def_chain_iterator &O) const { return MA == O.MA; }
396
397private:
398 MemoryAccess *MA;
399};
400
401static iterator_range<def_chain_iterator>
402def_chain(MemoryAccess *MA, MemoryAccess *UpTo = nullptr) {
403#ifdef EXPENSIVE_CHECKS
404 assert((!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator()) &&
405 "UpTo isn't in the def chain!");
406#endif
407 return make_range(def_chain_iterator(MA), def_chain_iterator(UpTo));
408}
409
410/// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
411/// inbetween `Start` and `ClobberAt` can clobbers `Start`.
412///
413/// This is meant to be as simple and self-contained as possible. Because it
414/// uses no cache, etc., it can be relatively expensive.
415///
416/// \param Start The MemoryAccess that we want to walk from.
417/// \param ClobberAt A clobber for Start.
418/// \param StartLoc The MemoryLocation for Start.
419/// \param MSSA The MemorySSA isntance that Start and ClobberAt belong to.
420/// \param Query The UpwardsMemoryQuery we used for our search.
421/// \param AA The AliasAnalysis we used for our search.
422static void LLVM_ATTRIBUTE_UNUSED
423checkClobberSanity(MemoryAccess *Start, MemoryAccess *ClobberAt,
424 const MemoryLocation &StartLoc, const MemorySSA &MSSA,
425 const UpwardsMemoryQuery &Query, AliasAnalysis &AA) {
426 assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
427
428 if (MSSA.isLiveOnEntryDef(Start)) {
429 assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
430 "liveOnEntry must clobber itself");
431 return;
432 }
433
George Burgess IV5f308972016-07-19 01:29:15 +0000434 bool FoundClobber = false;
435 DenseSet<MemoryAccessPair> VisitedPhis;
436 SmallVector<MemoryAccessPair, 8> Worklist;
437 Worklist.emplace_back(Start, StartLoc);
438 // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
439 // is found, complain.
440 while (!Worklist.empty()) {
441 MemoryAccessPair MAP = Worklist.pop_back_val();
442 // All we care about is that nothing from Start to ClobberAt clobbers Start.
443 // We learn nothing from revisiting nodes.
444 if (!VisitedPhis.insert(MAP).second)
445 continue;
446
447 for (MemoryAccess *MA : def_chain(MAP.first)) {
448 if (MA == ClobberAt) {
449 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
450 // instructionClobbersQuery isn't essentially free, so don't use `|=`,
451 // since it won't let us short-circuit.
452 //
453 // Also, note that this can't be hoisted out of the `Worklist` loop,
454 // since MD may only act as a clobber for 1 of N MemoryLocations.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000455 FoundClobber =
456 FoundClobber || MSSA.isLiveOnEntryDef(MD) ||
457 instructionClobbersQuery(MD, MAP.second, Query.Inst, AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000458 }
459 break;
460 }
461
462 // We should never hit liveOnEntry, unless it's the clobber.
463 assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
464
465 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
466 (void)MD;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000467 assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA) &&
George Burgess IV5f308972016-07-19 01:29:15 +0000468 "Found clobber before reaching ClobberAt!");
469 continue;
470 }
471
472 assert(isa<MemoryPhi>(MA));
473 Worklist.append(upward_defs_begin({MA, MAP.second}), upward_defs_end());
474 }
475 }
476
477 // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
478 // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
479 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
480 "ClobberAt never acted as a clobber");
481}
482
483/// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
484/// in one class.
485class ClobberWalker {
486 /// Save a few bytes by using unsigned instead of size_t.
487 using ListIndex = unsigned;
488
489 /// Represents a span of contiguous MemoryDefs, potentially ending in a
490 /// MemoryPhi.
491 struct DefPath {
492 MemoryLocation Loc;
493 // Note that, because we always walk in reverse, Last will always dominate
494 // First. Also note that First and Last are inclusive.
495 MemoryAccess *First;
496 MemoryAccess *Last;
497 // N.B. Blocker is currently basically unused. The goal is to use it to make
498 // cache invalidation better, but we're not there yet.
499 MemoryAccess *Blocker;
500 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)
841 // For the moment, this is fine, since we do basically nothing with
842 // blocker info.
George Burgess IV14633b52016-08-03 01:22:19 +0000843 if (Optional<TerminatedPath> Blocker = getBlockingAccess(
George Burgess IV5f308972016-07-19 01:29:15 +0000844 Target, PausedSearches, NewPaused, TerminatedPaths)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000845 // Cache our work on the blocking node, since we know that's correct.
George Burgess IV14633b52016-08-03 01:22:19 +0000846 cacheDefPath(Paths[Blocker->LastNode], Blocker->Clobber);
George Burgess IV5f308972016-07-19 01:29:15 +0000847
848 // Find the node we started at. We can't search based on N->Last, since
849 // we may have gone around a loop with a different MemoryLocation.
George Burgess IV14633b52016-08-03 01:22:19 +0000850 auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
George Burgess IV5f308972016-07-19 01:29:15 +0000851 return defPathIndex(N) < PriorPathsSize;
852 });
853 assert(Iter != def_path_iterator());
854
855 DefPath &CurNode = *Iter;
856 assert(CurNode.Last == Current);
George Burgess IV14633b52016-08-03 01:22:19 +0000857 CurNode.Blocker = Blocker->Clobber;
George Burgess IV5f308972016-07-19 01:29:15 +0000858
859 // Two things:
860 // A. We can't reliably cache all of NewPaused back. Consider a case
861 // where we have two paths in NewPaused; one of which can't optimize
862 // above this phi, whereas the other can. If we cache the second path
863 // back, we'll end up with suboptimal cache entries. We can handle
864 // cases like this a bit better when we either try to find all
865 // clobbers that block phi optimization, or when our cache starts
866 // supporting unfinished searches.
867 // B. We can't reliably cache TerminatedPaths back here without doing
868 // extra checks; consider a case like:
869 // T
870 // / \
871 // D C
872 // \ /
873 // S
874 // Where T is our target, C is a node with a clobber on it, D is a
875 // diamond (with a clobber *only* on the left or right node, N), and
876 // S is our start. Say we walk to D, through the node opposite N
877 // (read: ignoring the clobber), and see a cache entry in the top
878 // node of D. That cache entry gets put into TerminatedPaths. We then
879 // walk up to C (N is later in our worklist), find the clobber, and
880 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
881 // the bottom part of D to the cached clobber, ignoring the clobber
882 // in N. Again, this problem goes away if we start tracking all
883 // blockers for a given phi optimization.
884 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
885 return {Result, {}};
886 }
887
888 // If there's nothing left to search, then all paths led to valid clobbers
889 // that we got from our cache; pick the nearest to the start, and allow
890 // the rest to be cached back.
891 if (NewPaused.empty()) {
892 MoveDominatedPathToEnd(TerminatedPaths);
893 TerminatedPath Result = TerminatedPaths.pop_back_val();
894 return {Result, std::move(TerminatedPaths)};
895 }
896
897 MemoryAccess *DefChainEnd = nullptr;
898 SmallVector<TerminatedPath, 4> Clobbers;
899 for (ListIndex Paused : NewPaused) {
900 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
901 if (WR.IsKnownClobber)
902 Clobbers.push_back({WR.Result, Paused});
903 else
904 // Micro-opt: If we hit the end of the chain, save it.
905 DefChainEnd = WR.Result;
906 }
907
908 if (!TerminatedPaths.empty()) {
909 // If we couldn't find the dominating phi/liveOnEntry in the above loop,
910 // do it now.
911 if (!DefChainEnd)
912 for (MemoryAccess *MA : def_chain(Target))
913 DefChainEnd = MA;
914
915 // If any of the terminated paths don't dominate the phi we'll try to
916 // optimize, we need to figure out what they are and quit.
917 const BasicBlock *ChainBB = DefChainEnd->getBlock();
918 for (const TerminatedPath &TP : TerminatedPaths) {
919 // Because we know that DefChainEnd is as "high" as we can go, we
920 // don't need local dominance checks; BB dominance is sufficient.
921 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
922 Clobbers.push_back(TP);
923 }
924 }
925
926 // If we have clobbers in the def chain, find the one closest to Current
927 // and quit.
928 if (!Clobbers.empty()) {
929 MoveDominatedPathToEnd(Clobbers);
930 TerminatedPath Result = Clobbers.pop_back_val();
931 return {Result, std::move(Clobbers)};
932 }
933
934 assert(all_of(NewPaused,
935 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
936
937 // Because liveOnEntry is a clobber, this must be a phi.
938 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
939
940 PriorPathsSize = Paths.size();
941 PausedSearches.clear();
942 for (ListIndex I : NewPaused)
943 addSearches(DefChainPhi, PausedSearches, I);
944 NewPaused.clear();
945
946 Current = DefChainPhi;
947 }
948 }
949
950 /// Caches everything in an OptznResult.
951 void cacheOptResult(const OptznResult &R) {
952 if (R.OtherClobbers.empty()) {
953 // If we're not going to be caching OtherClobbers, don't bother with
954 // marking visited/etc.
955 for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode))
956 cacheDefPath(N, R.PrimaryClobber.Clobber);
957 return;
958 }
959
960 // PrimaryClobber is our answer. If we can cache anything back, we need to
961 // stop caching when we visit PrimaryClobber.
962 SmallBitVector Visited(Paths.size());
963 for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode)) {
964 Visited[defPathIndex(N)] = true;
965 cacheDefPath(N, R.PrimaryClobber.Clobber);
966 }
967
968 for (const TerminatedPath &P : R.OtherClobbers) {
969 for (const DefPath &N : const_def_path(P.LastNode)) {
970 ListIndex NIndex = defPathIndex(N);
971 if (Visited[NIndex])
972 break;
973 Visited[NIndex] = true;
974 cacheDefPath(N, P.Clobber);
975 }
976 }
977 }
978
979 void verifyOptResult(const OptznResult &R) const {
980 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
981 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
982 }));
983 }
984
985 void resetPhiOptznState() {
986 Paths.clear();
987 VisitedPhis.clear();
988 }
989
990public:
991 ClobberWalker(const MemorySSA &MSSA, AliasAnalysis &AA, DominatorTree &DT,
992 WalkerCache &WC)
993 : MSSA(MSSA), AA(AA), DT(DT), WC(WC), UseCache(true) {}
994
995 void reset() { WalkTargetCache.clear(); }
996
997 /// Finds the nearest clobber for the given query, optimizing phis if
998 /// possible.
999 MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q,
1000 bool UseWalkerCache = true) {
1001 setUseCache(UseWalkerCache);
1002 Query = &Q;
1003
1004 MemoryAccess *Current = Start;
1005 // This walker pretends uses don't exist. If we're handed one, silently grab
1006 // its def. (This has the nice side-effect of ensuring we never cache uses)
1007 if (auto *MU = dyn_cast<MemoryUse>(Start))
1008 Current = MU->getDefiningAccess();
1009
1010 DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
1011 // Fast path for the overly-common case (no crazy phi optimization
1012 // necessary)
1013 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
George Burgess IV93ea19b2016-07-24 07:03:49 +00001014 MemoryAccess *Result;
George Burgess IV5f308972016-07-19 01:29:15 +00001015 if (WalkResult.IsKnownClobber) {
1016 cacheDefPath(FirstDesc, WalkResult.Result);
George Burgess IV93ea19b2016-07-24 07:03:49 +00001017 Result = WalkResult.Result;
1018 } else {
1019 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
1020 Current, Q.StartingLoc);
1021 verifyOptResult(OptRes);
1022 cacheOptResult(OptRes);
1023 resetPhiOptznState();
1024 Result = OptRes.PrimaryClobber.Clobber;
George Burgess IV5f308972016-07-19 01:29:15 +00001025 }
1026
George Burgess IV5f308972016-07-19 01:29:15 +00001027#ifdef EXPENSIVE_CHECKS
George Burgess IV93ea19b2016-07-24 07:03:49 +00001028 checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
George Burgess IV5f308972016-07-19 01:29:15 +00001029#endif
George Burgess IV93ea19b2016-07-24 07:03:49 +00001030 return Result;
George Burgess IV5f308972016-07-19 01:29:15 +00001031 }
1032};
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(); }
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001111};
George Burgess IVe1100f52016-02-02 22:46:49 +00001112
George Burgess IVe1100f52016-02-02 22:46:49 +00001113/// \brief Rename a single basic block into MemorySSA form.
1114/// Uses the standard SSA renaming algorithm.
1115/// \returns The new incoming value.
1116MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB,
1117 MemoryAccess *IncomingVal) {
1118 auto It = PerBlockAccesses.find(BB);
1119 // Skip most processing if the list is empty.
1120 if (It != PerBlockAccesses.end()) {
Daniel Berlinada263d2016-06-20 20:21:33 +00001121 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001122 for (MemoryAccess &L : *Accesses) {
1123 switch (L.getValueID()) {
1124 case Value::MemoryUseVal:
1125 cast<MemoryUse>(&L)->setDefiningAccess(IncomingVal);
1126 break;
1127 case Value::MemoryDefVal:
1128 // We can't legally optimize defs, because we only allow single
1129 // memory phis/uses on operations, and if we optimize these, we can
1130 // end up with multiple reaching defs. Uses do not have this
1131 // problem, since they do not produce a value
1132 cast<MemoryDef>(&L)->setDefiningAccess(IncomingVal);
1133 IncomingVal = &L;
1134 break;
1135 case Value::MemoryPhiVal:
1136 IncomingVal = &L;
1137 break;
1138 }
1139 }
1140 }
1141
1142 // Pass through values to our successors
1143 for (const BasicBlock *S : successors(BB)) {
1144 auto It = PerBlockAccesses.find(S);
1145 // Rename the phi nodes in our successor block
1146 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1147 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +00001148 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001149 auto *Phi = cast<MemoryPhi>(&Accesses->front());
George Burgess IVe1100f52016-02-02 22:46:49 +00001150 Phi->addIncoming(IncomingVal, BB);
1151 }
1152
1153 return IncomingVal;
1154}
1155
1156/// \brief This is the standard SSA renaming algorithm.
1157///
1158/// We walk the dominator tree in preorder, renaming accesses, and then filling
1159/// in phi nodes in our successors.
1160void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
1161 SmallPtrSet<BasicBlock *, 16> &Visited) {
1162 SmallVector<RenamePassData, 32> WorkStack;
1163 IncomingVal = renameBlock(Root->getBlock(), IncomingVal);
1164 WorkStack.push_back({Root, Root->begin(), IncomingVal});
1165 Visited.insert(Root->getBlock());
1166
1167 while (!WorkStack.empty()) {
1168 DomTreeNode *Node = WorkStack.back().DTN;
1169 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
1170 IncomingVal = WorkStack.back().IncomingVal;
1171
1172 if (ChildIt == Node->end()) {
1173 WorkStack.pop_back();
1174 } else {
1175 DomTreeNode *Child = *ChildIt;
1176 ++WorkStack.back().ChildIt;
1177 BasicBlock *BB = Child->getBlock();
1178 Visited.insert(BB);
1179 IncomingVal = renameBlock(BB, IncomingVal);
1180 WorkStack.push_back({Child, Child->begin(), IncomingVal});
1181 }
1182 }
1183}
1184
1185/// \brief Compute dominator levels, used by the phi insertion algorithm above.
1186void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) {
1187 for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode());
1188 DFI != DFE; ++DFI)
1189 DomLevels[*DFI] = DFI.getPathLength() - 1;
1190}
1191
George Burgess IVa362b092016-07-06 00:28:43 +00001192/// \brief This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +00001193/// unreachable blocks, and marking all other unreachable MemoryAccess's as
1194/// being uses of the live on entry definition.
1195void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
1196 assert(!DT->isReachableFromEntry(BB) &&
1197 "Reachable block found while handling unreachable blocks");
1198
Daniel Berlinfc7e6512016-07-06 05:32:05 +00001199 // Make sure phi nodes in our reachable successors end up with a
1200 // LiveOnEntryDef for our incoming edge, even though our block is forward
1201 // unreachable. We could just disconnect these blocks from the CFG fully,
1202 // but we do not right now.
1203 for (const BasicBlock *S : successors(BB)) {
1204 if (!DT->isReachableFromEntry(S))
1205 continue;
1206 auto It = PerBlockAccesses.find(S);
1207 // Rename the phi nodes in our successor block
1208 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1209 continue;
1210 AccessList *Accesses = It->second.get();
1211 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1212 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1213 }
1214
George Burgess IVe1100f52016-02-02 22:46:49 +00001215 auto It = PerBlockAccesses.find(BB);
1216 if (It == PerBlockAccesses.end())
1217 return;
1218
1219 auto &Accesses = It->second;
1220 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1221 auto Next = std::next(AI);
1222 // If we have a phi, just remove it. We are going to replace all
1223 // users with live on entry.
1224 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1225 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1226 else
1227 Accesses->erase(AI);
1228 AI = Next;
1229 }
1230}
1231
Geoff Berryb96d3b22016-06-01 21:30:40 +00001232MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
1233 : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
1234 NextID(0) {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001235 buildMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001236}
1237
1238MemorySSA::MemorySSA(MemorySSA &&MSSA)
1239 : AA(MSSA.AA), DT(MSSA.DT), F(MSSA.F),
1240 ValueToMemoryAccess(std::move(MSSA.ValueToMemoryAccess)),
1241 PerBlockAccesses(std::move(MSSA.PerBlockAccesses)),
1242 LiveOnEntryDef(std::move(MSSA.LiveOnEntryDef)),
1243 Walker(std::move(MSSA.Walker)), NextID(MSSA.NextID) {
1244 // Update the Walker MSSA pointer so it doesn't point to the moved-from MSSA
1245 // object any more.
1246 Walker->MSSA = this;
1247}
George Burgess IVe1100f52016-02-02 22:46:49 +00001248
1249MemorySSA::~MemorySSA() {
1250 // Drop all our references
1251 for (const auto &Pair : PerBlockAccesses)
1252 for (MemoryAccess &MA : *Pair.second)
1253 MA.dropAllReferences();
1254}
1255
Daniel Berlin14300262016-06-21 18:39:20 +00001256MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001257 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1258
1259 if (Res.second)
Daniel Berlinada263d2016-06-20 20:21:33 +00001260 Res.first->second = make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001261 return Res.first->second.get();
1262}
1263
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001264/// This class is a batch walker of all MemoryUse's in the program, and points
1265/// their defining access at the thing that actually clobbers them. Because it
1266/// is a batch walker that touches everything, it does not operate like the
1267/// other walkers. This walker is basically performing a top-down SSA renaming
1268/// pass, where the version stack is used as the cache. This enables it to be
1269/// significantly more time and memory efficient than using the regular walker,
1270/// which is walking bottom-up.
1271class MemorySSA::OptimizeUses {
1272public:
1273 OptimizeUses(MemorySSA *MSSA, MemorySSAWalker *Walker, AliasAnalysis *AA,
1274 DominatorTree *DT)
1275 : MSSA(MSSA), Walker(Walker), AA(AA), DT(DT) {
1276 Walker = MSSA->getWalker();
1277 }
1278
1279 void optimizeUses();
1280
1281private:
1282 /// This represents where a given memorylocation is in the stack.
1283 struct MemlocStackInfo {
1284 // This essentially is keeping track of versions of the stack. Whenever
1285 // the stack changes due to pushes or pops, these versions increase.
1286 unsigned long StackEpoch;
1287 unsigned long PopEpoch;
1288 // This is the lower bound of places on the stack to check. It is equal to
1289 // the place the last stack walk ended.
1290 // Note: Correctness depends on this being initialized to 0, which densemap
1291 // does
1292 unsigned long LowerBound;
1293 // This is where the last walk for this memory location ended.
1294 unsigned long LastKill;
1295 bool LastKillValid;
1296 };
1297 void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1298 SmallVectorImpl<MemoryAccess *> &,
1299 DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
1300 MemorySSA *MSSA;
1301 MemorySSAWalker *Walker;
1302 AliasAnalysis *AA;
1303 DominatorTree *DT;
1304};
1305
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001306/// Optimize the uses in a given block This is basically the SSA renaming
1307/// algorithm, with one caveat: We are able to use a single stack for all
1308/// MemoryUses. This is because the set of *possible* reaching MemoryDefs is
1309/// the same for every MemoryUse. The *actual* clobbering MemoryDef is just
1310/// going to be some position in that stack of possible ones.
1311///
1312/// We track the stack positions that each MemoryLocation needs
1313/// to check, and last ended at. This is because we only want to check the
1314/// things that changed since last time. The same MemoryLocation should
1315/// get clobbered by the same store (getModRefInfo does not use invariantness or
1316/// things like this, and if they start, we can modify MemoryLocOrCall to
1317/// include relevant data)
1318void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1319 const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1320 SmallVectorImpl<MemoryAccess *> &VersionStack,
1321 DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
1322
1323 /// If no accesses, nothing to do.
1324 MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
1325 if (Accesses == nullptr)
1326 return;
1327
1328 // Pop everything that doesn't dominate the current block off the stack,
1329 // increment the PopEpoch to account for this.
1330 while (!VersionStack.empty()) {
1331 BasicBlock *BackBlock = VersionStack.back()->getBlock();
1332 if (DT->dominates(BackBlock, BB))
1333 break;
1334 while (VersionStack.back()->getBlock() == BackBlock)
1335 VersionStack.pop_back();
1336 ++PopEpoch;
1337 }
1338
1339 for (MemoryAccess &MA : *Accesses) {
1340 auto *MU = dyn_cast<MemoryUse>(&MA);
1341 if (!MU) {
1342 VersionStack.push_back(&MA);
1343 ++StackEpoch;
1344 continue;
1345 }
1346
George Burgess IV024f3d22016-08-03 19:57:02 +00001347 if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
1348 MU->setDefiningAccess(MSSA->getLiveOnEntryDef());
1349 continue;
1350 }
1351
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001352 MemoryLocOrCall UseMLOC(MU);
1353 auto &LocInfo = LocStackInfo[UseMLOC];
Daniel Berlin26fcea92016-08-02 20:02:21 +00001354 // If the pop epoch changed, it means we've removed stuff from top of
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001355 // stack due to changing blocks. We may have to reset the lower bound or
1356 // last kill info.
1357 if (LocInfo.PopEpoch != PopEpoch) {
1358 LocInfo.PopEpoch = PopEpoch;
1359 LocInfo.StackEpoch = StackEpoch;
1360 // If the lower bound was in the info we popped, we have to reset it.
1361 if (LocInfo.LowerBound >= VersionStack.size()) {
1362 // Reset the lower bound of things to check.
1363 // TODO: Some day we should be able to reset to last kill, rather than
1364 // 0.
1365
1366 LocInfo.LowerBound = 0;
1367 LocInfo.LastKillValid = false;
1368 }
1369 } else if (LocInfo.StackEpoch != StackEpoch) {
1370 // If all that has changed is the StackEpoch, we only have to check the
1371 // new things on the stack, because we've checked everything before. In
1372 // this case, the lower bound of things to check remains the same.
1373 LocInfo.PopEpoch = PopEpoch;
1374 LocInfo.StackEpoch = StackEpoch;
1375 }
1376 if (!LocInfo.LastKillValid) {
1377 LocInfo.LastKill = VersionStack.size() - 1;
1378 LocInfo.LastKillValid = true;
1379 }
1380
1381 // At this point, we should have corrected last kill and LowerBound to be
1382 // in bounds.
1383 assert(LocInfo.LowerBound < VersionStack.size() &&
1384 "Lower bound out of range");
1385 assert(LocInfo.LastKill < VersionStack.size() &&
1386 "Last kill info out of range");
1387 // In any case, the new upper bound is the top of the stack.
1388 unsigned long UpperBound = VersionStack.size() - 1;
1389
1390 if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
Daniel Berlin26fcea92016-08-02 20:02:21 +00001391 DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
1392 << *(MU->getMemoryInst()) << ")"
1393 << " because there are " << UpperBound - LocInfo.LowerBound
1394 << " stores to disambiguate\n");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001395 // Because we did not walk, LastKill is no longer valid, as this may
1396 // have been a kill.
1397 LocInfo.LastKillValid = false;
1398 continue;
1399 }
1400 bool FoundClobberResult = false;
1401 while (UpperBound > LocInfo.LowerBound) {
1402 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1403 // For phis, use the walker, see where we ended up, go there
1404 Instruction *UseInst = MU->getMemoryInst();
1405 MemoryAccess *Result = Walker->getClobberingMemoryAccess(UseInst);
1406 // We are guaranteed to find it or something is wrong
1407 while (VersionStack[UpperBound] != Result) {
1408 assert(UpperBound != 0);
1409 --UpperBound;
1410 }
1411 FoundClobberResult = true;
1412 break;
1413 }
1414
1415 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
Daniel Berlindf101192016-08-03 00:01:46 +00001416 // If the lifetime of the pointer ends at this instruction, it's live on
1417 // entry.
1418 if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1419 // Reset UpperBound to liveOnEntryDef's place in the stack
1420 UpperBound = 0;
1421 FoundClobberResult = true;
1422 break;
1423 }
Daniel Berlindff31de2016-08-02 21:57:52 +00001424 if (instructionClobbersQuery(MD, MU, UseMLOC, *AA)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001425 FoundClobberResult = true;
1426 break;
1427 }
1428 --UpperBound;
1429 }
1430 // At the end of this loop, UpperBound is either a clobber, or lower bound
1431 // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1432 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
1433 MU->setDefiningAccess(VersionStack[UpperBound]);
1434 // We were last killed now by where we got to
1435 LocInfo.LastKill = UpperBound;
1436 } else {
1437 // Otherwise, we checked all the new ones, and now we know we can get to
1438 // LastKill.
1439 MU->setDefiningAccess(VersionStack[LocInfo.LastKill]);
1440 }
1441 LocInfo.LowerBound = VersionStack.size() - 1;
1442 }
1443}
1444
1445/// Optimize uses to point to their actual clobbering definitions.
1446void MemorySSA::OptimizeUses::optimizeUses() {
1447
1448 // We perform a non-recursive top-down dominator tree walk
1449 struct StackInfo {
1450 const DomTreeNode *Node;
1451 DomTreeNode::const_iterator Iter;
1452 };
1453
1454 SmallVector<MemoryAccess *, 16> VersionStack;
1455 SmallVector<StackInfo, 16> DomTreeWorklist;
1456 DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
1457 DomTreeWorklist.push_back({DT->getRootNode(), DT->getRootNode()->begin()});
1458 // Bottom of the version stack is always live on entry.
1459 VersionStack.push_back(MSSA->getLiveOnEntryDef());
1460
1461 unsigned long StackEpoch = 1;
1462 unsigned long PopEpoch = 1;
1463 while (!DomTreeWorklist.empty()) {
1464 const auto *DomNode = DomTreeWorklist.back().Node;
1465 const auto DomIter = DomTreeWorklist.back().Iter;
1466 BasicBlock *BB = DomNode->getBlock();
1467 optimizeUsesInBlock(BB, StackEpoch, PopEpoch, VersionStack, LocStackInfo);
1468 if (DomIter == DomNode->end()) {
1469 // Hit the end, pop the worklist
1470 DomTreeWorklist.pop_back();
1471 continue;
1472 }
1473 // Move the iterator to the next child for the next time we get to process
1474 // children
1475 ++DomTreeWorklist.back().Iter;
1476
1477 // Now visit the next child
1478 DomTreeWorklist.push_back({*DomIter, (*DomIter)->begin()});
1479 }
1480}
1481
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001482void MemorySSA::buildMemorySSA() {
George Burgess IVe1100f52016-02-02 22:46:49 +00001483 // We create an access to represent "live on entry", for things like
1484 // arguments or users of globals, where the memory they use is defined before
1485 // the beginning of the function. We do not actually insert it into the IR.
1486 // We do not define a live on exit for the immediate uses, and thus our
1487 // semantics do *not* imply that something with no immediate uses can simply
1488 // be removed.
1489 BasicBlock &StartingPoint = F.getEntryBlock();
1490 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
1491 &StartingPoint, NextID++);
1492
1493 // We maintain lists of memory accesses per-block, trading memory for time. We
1494 // could just look up the memory access for every possible instruction in the
1495 // stream.
1496 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001497 SmallPtrSet<BasicBlock *, 32> DefUseBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001498 // Go through each block, figure out where defs occur, and chain together all
1499 // the accesses.
1500 for (BasicBlock &B : F) {
Daniel Berlin7898ca62016-02-07 01:52:15 +00001501 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001502 AccessList *Accesses = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001503 for (Instruction &I : B) {
Peter Collingbourneffecb142016-05-26 01:19:17 +00001504 MemoryUseOrDef *MUD = createNewAccess(&I);
George Burgess IVb42b7622016-03-11 19:34:03 +00001505 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001506 continue;
George Burgess IV3887a412016-03-21 21:25:39 +00001507 InsertIntoDef |= isa<MemoryDef>(MUD);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001508
George Burgess IVe1100f52016-02-02 22:46:49 +00001509 if (!Accesses)
1510 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001511 Accesses->push_back(MUD);
George Burgess IVe1100f52016-02-02 22:46:49 +00001512 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001513 if (InsertIntoDef)
1514 DefiningBlocks.insert(&B);
George Burgess IV3887a412016-03-21 21:25:39 +00001515 if (Accesses)
Daniel Berlin1b51a292016-02-07 01:52:19 +00001516 DefUseBlocks.insert(&B);
1517 }
1518
1519 // Compute live-in.
1520 // Live in is normally defined as "all the blocks on the path from each def to
1521 // each of it's uses".
1522 // MemoryDef's are implicit uses of previous state, so they are also uses.
1523 // This means we don't really have def-only instructions. The only
1524 // MemoryDef's that are not really uses are those that are of the LiveOnEntry
1525 // variable (because LiveOnEntry can reach anywhere, and every def is a
1526 // must-kill of LiveOnEntry).
1527 // In theory, you could precisely compute live-in by using alias-analysis to
1528 // disambiguate defs and uses to see which really pair up with which.
1529 // In practice, this would be really expensive and difficult. So we simply
1530 // assume all defs are also uses that need to be kept live.
1531 // Because of this, the end result of this live-in computation will be "the
1532 // entire set of basic blocks that reach any use".
1533
1534 SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
1535 SmallVector<BasicBlock *, 64> LiveInBlockWorklist(DefUseBlocks.begin(),
1536 DefUseBlocks.end());
1537 // Now that we have a set of blocks where a value is live-in, recursively add
1538 // predecessors until we find the full region the value is live.
1539 while (!LiveInBlockWorklist.empty()) {
1540 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
1541
1542 // The block really is live in here, insert it into the set. If already in
1543 // the set, then it has already been processed.
1544 if (!LiveInBlocks.insert(BB).second)
1545 continue;
1546
1547 // Since the value is live into BB, it is either defined in a predecessor or
1548 // live into it to.
1549 LiveInBlockWorklist.append(pred_begin(BB), pred_end(BB));
George Burgess IVe1100f52016-02-02 22:46:49 +00001550 }
1551
1552 // Determine where our MemoryPhi's should go
Daniel Berlin77fa84e2016-04-19 06:13:28 +00001553 ForwardIDFCalculator IDFs(*DT);
George Burgess IVe1100f52016-02-02 22:46:49 +00001554 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001555 IDFs.setLiveInBlocks(LiveInBlocks);
George Burgess IVe1100f52016-02-02 22:46:49 +00001556 SmallVector<BasicBlock *, 32> IDFBlocks;
1557 IDFs.calculate(IDFBlocks);
1558
1559 // Now place MemoryPhi nodes.
1560 for (auto &BB : IDFBlocks) {
1561 // Insert phi node
Daniel Berlinada263d2016-06-20 20:21:33 +00001562 AccessList *Accesses = getOrCreateAccessList(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001563 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001564 ValueToMemoryAccess[BB] = Phi;
George Burgess IVe1100f52016-02-02 22:46:49 +00001565 // Phi's always are placed at the front of the block.
1566 Accesses->push_front(Phi);
1567 }
1568
1569 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1570 // filled in with all blocks.
1571 SmallPtrSet<BasicBlock *, 16> Visited;
1572 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1573
George Burgess IV5f308972016-07-19 01:29:15 +00001574 CachingWalker *Walker = getWalkerImpl();
1575
1576 // We're doing a batch of updates; don't drop useful caches between them.
1577 Walker->setAutoResetWalker(false);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001578 OptimizeUses(this, Walker, AA, DT).optimizeUses();
George Burgess IV5f308972016-07-19 01:29:15 +00001579 Walker->setAutoResetWalker(true);
1580 Walker->resetClobberWalker();
1581
George Burgess IVe1100f52016-02-02 22:46:49 +00001582 // Mark the uses in unreachable blocks as live on entry, so that they go
1583 // somewhere.
1584 for (auto &BB : F)
1585 if (!Visited.count(&BB))
1586 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001587}
George Burgess IVe1100f52016-02-02 22:46:49 +00001588
George Burgess IV5f308972016-07-19 01:29:15 +00001589MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1590
1591MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001592 if (Walker)
1593 return Walker.get();
1594
1595 Walker = make_unique<CachingWalker>(this, AA, DT);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001596 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001597}
1598
Daniel Berlin14300262016-06-21 18:39:20 +00001599MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1600 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
1601 AccessList *Accesses = getOrCreateAccessList(BB);
1602 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001603 ValueToMemoryAccess[BB] = Phi;
Daniel Berlin14300262016-06-21 18:39:20 +00001604 // Phi's always are placed at the front of the block.
1605 Accesses->push_front(Phi);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001606 BlockNumberingValid.erase(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001607 return Phi;
1608}
1609
1610MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
1611 MemoryAccess *Definition) {
1612 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1613 MemoryUseOrDef *NewAccess = createNewAccess(I);
1614 assert(
1615 NewAccess != nullptr &&
1616 "Tried to create a memory access for a non-memory touching instruction");
1617 NewAccess->setDefiningAccess(Definition);
1618 return NewAccess;
1619}
1620
1621MemoryAccess *MemorySSA::createMemoryAccessInBB(Instruction *I,
1622 MemoryAccess *Definition,
1623 const BasicBlock *BB,
1624 InsertionPlace Point) {
1625 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1626 auto *Accesses = getOrCreateAccessList(BB);
1627 if (Point == Beginning) {
1628 // It goes after any phi nodes
1629 auto AI = std::find_if(
1630 Accesses->begin(), Accesses->end(),
1631 [](const MemoryAccess &MA) { return !isa<MemoryPhi>(MA); });
1632
1633 Accesses->insert(AI, NewAccess);
1634 } else {
1635 Accesses->push_back(NewAccess);
1636 }
Daniel Berlin5c46b942016-07-19 22:49:43 +00001637 BlockNumberingValid.erase(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001638 return NewAccess;
1639}
1640MemoryAccess *MemorySSA::createMemoryAccessBefore(Instruction *I,
1641 MemoryAccess *Definition,
1642 MemoryAccess *InsertPt) {
1643 assert(I->getParent() == InsertPt->getBlock() &&
1644 "New and old access must be in the same block");
1645 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1646 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
1647 Accesses->insert(AccessList::iterator(InsertPt), NewAccess);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001648 BlockNumberingValid.erase(InsertPt->getBlock());
Daniel Berlin14300262016-06-21 18:39:20 +00001649 return NewAccess;
1650}
1651
1652MemoryAccess *MemorySSA::createMemoryAccessAfter(Instruction *I,
1653 MemoryAccess *Definition,
1654 MemoryAccess *InsertPt) {
1655 assert(I->getParent() == InsertPt->getBlock() &&
1656 "New and old access must be in the same block");
1657 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1658 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
1659 Accesses->insertAfter(AccessList::iterator(InsertPt), NewAccess);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001660 BlockNumberingValid.erase(InsertPt->getBlock());
Daniel Berlin14300262016-06-21 18:39:20 +00001661 return NewAccess;
1662}
1663
George Burgess IVe1100f52016-02-02 22:46:49 +00001664/// \brief Helper function to create new memory accesses
Peter Collingbourneffecb142016-05-26 01:19:17 +00001665MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001666 // The assume intrinsic has a control dependency which we model by claiming
1667 // that it writes arbitrarily. Ignore that fake memory dependency here.
1668 // FIXME: Replace this special casing with a more accurate modelling of
1669 // assume's control dependency.
1670 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1671 if (II->getIntrinsicID() == Intrinsic::assume)
1672 return nullptr;
1673
George Burgess IVe1100f52016-02-02 22:46:49 +00001674 // Find out what affect this instruction has on memory.
1675 ModRefInfo ModRef = AA->getModRefInfo(I);
1676 bool Def = bool(ModRef & MRI_Mod);
1677 bool Use = bool(ModRef & MRI_Ref);
1678
1679 // It's possible for an instruction to not modify memory at all. During
1680 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +00001681 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +00001682 return nullptr;
1683
1684 assert((Def || Use) &&
1685 "Trying to create a memory access with a non-memory instruction");
1686
George Burgess IVb42b7622016-03-11 19:34:03 +00001687 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001688 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +00001689 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +00001690 else
George Burgess IVb42b7622016-03-11 19:34:03 +00001691 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
Daniel Berlin5130cc82016-07-31 21:08:20 +00001692 ValueToMemoryAccess[I] = MUD;
George Burgess IVb42b7622016-03-11 19:34:03 +00001693 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001694}
1695
1696MemoryAccess *MemorySSA::findDominatingDef(BasicBlock *UseBlock,
1697 enum InsertionPlace Where) {
1698 // Handle the initial case
1699 if (Where == Beginning)
1700 // The only thing that could define us at the beginning is a phi node
1701 if (MemoryPhi *Phi = getMemoryAccess(UseBlock))
1702 return Phi;
1703
1704 DomTreeNode *CurrNode = DT->getNode(UseBlock);
1705 // Need to be defined by our dominator
1706 if (Where == Beginning)
1707 CurrNode = CurrNode->getIDom();
1708 Where = End;
1709 while (CurrNode) {
1710 auto It = PerBlockAccesses.find(CurrNode->getBlock());
1711 if (It != PerBlockAccesses.end()) {
1712 auto &Accesses = It->second;
David Majnemerd7708772016-06-24 04:05:21 +00001713 for (MemoryAccess &RA : reverse(*Accesses)) {
1714 if (isa<MemoryDef>(RA) || isa<MemoryPhi>(RA))
1715 return &RA;
George Burgess IVe1100f52016-02-02 22:46:49 +00001716 }
1717 }
1718 CurrNode = CurrNode->getIDom();
1719 }
1720 return LiveOnEntryDef.get();
1721}
1722
1723/// \brief Returns true if \p Replacer dominates \p Replacee .
1724bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1725 const MemoryAccess *Replacee) const {
1726 if (isa<MemoryUseOrDef>(Replacee))
1727 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1728 const auto *MP = cast<MemoryPhi>(Replacee);
1729 // For a phi node, the use occurs in the predecessor block of the phi node.
1730 // Since we may occur multiple times in the phi node, we have to check each
1731 // operand to ensure Replacer dominates each operand where Replacee occurs.
1732 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +00001733 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +00001734 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1735 return false;
1736 }
1737 return true;
1738}
1739
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001740/// \brief If all arguments of a MemoryPHI are defined by the same incoming
1741/// argument, return that argument.
1742static MemoryAccess *onlySingleValue(MemoryPhi *MP) {
1743 MemoryAccess *MA = nullptr;
1744
1745 for (auto &Arg : MP->operands()) {
1746 if (!MA)
1747 MA = cast<MemoryAccess>(Arg);
1748 else if (MA != Arg)
1749 return nullptr;
1750 }
1751 return MA;
1752}
1753
1754/// \brief Properly remove \p MA from all of MemorySSA's lookup tables.
1755///
1756/// Because of the way the intrusive list and use lists work, it is important to
1757/// do removal in the right order.
1758void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1759 assert(MA->use_empty() &&
1760 "Trying to remove memory access that still has uses");
Daniel Berlin5c46b942016-07-19 22:49:43 +00001761 BlockNumbering.erase(MA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001762 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
1763 MUD->setDefiningAccess(nullptr);
1764 // Invalidate our walker's cache if necessary
1765 if (!isa<MemoryUse>(MA))
1766 Walker->invalidateInfo(MA);
1767 // The call below to erase will destroy MA, so we can't change the order we
1768 // are doing things here
1769 Value *MemoryInst;
1770 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1771 MemoryInst = MUD->getMemoryInst();
1772 } else {
1773 MemoryInst = MA->getBlock();
1774 }
Daniel Berlin5130cc82016-07-31 21:08:20 +00001775 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1776 if (VMA->second == MA)
1777 ValueToMemoryAccess.erase(VMA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001778
George Burgess IVe0e6e482016-03-02 02:35:04 +00001779 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
Daniel Berlinada263d2016-06-20 20:21:33 +00001780 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001781 Accesses->erase(MA);
George Burgess IVe0e6e482016-03-02 02:35:04 +00001782 if (Accesses->empty())
1783 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001784}
1785
1786void MemorySSA::removeMemoryAccess(MemoryAccess *MA) {
1787 assert(!isLiveOnEntryDef(MA) && "Trying to remove the live on entry def");
1788 // We can only delete phi nodes if they have no uses, or we can replace all
1789 // uses with a single definition.
1790 MemoryAccess *NewDefTarget = nullptr;
1791 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) {
1792 // Note that it is sufficient to know that all edges of the phi node have
1793 // the same argument. If they do, by the definition of dominance frontiers
1794 // (which we used to place this phi), that argument must dominate this phi,
1795 // and thus, must dominate the phi's uses, and so we will not hit the assert
1796 // below.
1797 NewDefTarget = onlySingleValue(MP);
1798 assert((NewDefTarget || MP->use_empty()) &&
1799 "We can't delete this memory phi");
1800 } else {
1801 NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
1802 }
1803
1804 // Re-point the uses at our defining access
1805 if (!MA->use_empty())
1806 MA->replaceAllUsesWith(NewDefTarget);
1807
1808 // The call below to erase will destroy MA, so we can't change the order we
1809 // are doing things here
1810 removeFromLookups(MA);
1811}
1812
George Burgess IVe1100f52016-02-02 22:46:49 +00001813void MemorySSA::print(raw_ostream &OS) const {
1814 MemorySSAAnnotatedWriter Writer(this);
1815 F.print(OS, &Writer);
1816}
1817
1818void MemorySSA::dump() const {
1819 MemorySSAAnnotatedWriter Writer(this);
1820 F.print(dbgs(), &Writer);
1821}
1822
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001823void MemorySSA::verifyMemorySSA() const {
1824 verifyDefUses(F);
1825 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001826 verifyOrdering(F);
1827}
1828
1829/// \brief Verify that the order and existence of MemoryAccesses matches the
1830/// order and existence of memory affecting instructions.
1831void MemorySSA::verifyOrdering(Function &F) const {
1832 // Walk all the blocks, comparing what the lookups think and what the access
1833 // lists think, as well as the order in the blocks vs the order in the access
1834 // lists.
1835 SmallVector<MemoryAccess *, 32> ActualAccesses;
1836 for (BasicBlock &B : F) {
1837 const AccessList *AL = getBlockAccesses(&B);
1838 MemoryAccess *Phi = getMemoryAccess(&B);
1839 if (Phi)
1840 ActualAccesses.push_back(Phi);
1841 for (Instruction &I : B) {
1842 MemoryAccess *MA = getMemoryAccess(&I);
1843 assert((!MA || AL) && "We have memory affecting instructions "
1844 "in this block but they are not in the "
1845 "access list");
1846 if (MA)
1847 ActualAccesses.push_back(MA);
1848 }
1849 // Either we hit the assert, really have no accesses, or we have both
1850 // accesses and an access list
1851 if (!AL)
1852 continue;
1853 assert(AL->size() == ActualAccesses.size() &&
1854 "We don't have the same number of accesses in the block as on the "
1855 "access list");
1856 auto ALI = AL->begin();
1857 auto AAI = ActualAccesses.begin();
1858 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1859 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1860 ++ALI;
1861 ++AAI;
1862 }
1863 ActualAccesses.clear();
1864 }
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001865}
1866
George Burgess IVe1100f52016-02-02 22:46:49 +00001867/// \brief Verify the domination properties of MemorySSA by checking that each
1868/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001869void MemorySSA::verifyDomination(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001870 for (BasicBlock &B : F) {
1871 // Phi nodes are attached to basic blocks
1872 if (MemoryPhi *MP = getMemoryAccess(&B)) {
1873 for (User *U : MP->users()) {
1874 BasicBlock *UseBlock;
1875 // Phi operands are used on edges, we simulate the right domination by
1876 // acting as if the use occurred at the end of the predecessor block.
1877 if (MemoryPhi *P = dyn_cast<MemoryPhi>(U)) {
1878 for (const auto &Arg : P->operands()) {
1879 if (Arg == MP) {
1880 UseBlock = P->getIncomingBlock(Arg);
1881 break;
1882 }
1883 }
1884 } else {
1885 UseBlock = cast<MemoryAccess>(U)->getBlock();
1886 }
George Burgess IV60adac42016-02-02 23:26:01 +00001887 (void)UseBlock;
George Burgess IVe1100f52016-02-02 22:46:49 +00001888 assert(DT->dominates(MP->getBlock(), UseBlock) &&
1889 "Memory PHI does not dominate it's uses");
1890 }
1891 }
1892
1893 for (Instruction &I : B) {
1894 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
1895 if (!MD)
1896 continue;
1897
Benjamin Kramer451f54c2016-02-22 13:11:58 +00001898 for (User *U : MD->users()) {
Daniel Berlinada263d2016-06-20 20:21:33 +00001899 BasicBlock *UseBlock;
1900 (void)UseBlock;
George Burgess IVe1100f52016-02-02 22:46:49 +00001901 // Things are allowed to flow to phi nodes over their predecessor edge.
1902 if (auto *P = dyn_cast<MemoryPhi>(U)) {
1903 for (const auto &Arg : P->operands()) {
1904 if (Arg == MD) {
1905 UseBlock = P->getIncomingBlock(Arg);
1906 break;
1907 }
1908 }
1909 } else {
1910 UseBlock = cast<MemoryAccess>(U)->getBlock();
1911 }
1912 assert(DT->dominates(MD->getBlock(), UseBlock) &&
1913 "Memory Def does not dominate it's uses");
1914 }
1915 }
1916 }
1917}
1918
1919/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
1920/// appears in the use list of \p Def.
1921///
1922/// llvm_unreachable is used instead of asserts because this may be called in
1923/// a build without asserts. In that case, we don't want this to turn into a
1924/// nop.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001925void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001926 // The live on entry use may cause us to get a NULL def here
1927 if (!Def) {
1928 if (!isLiveOnEntryDef(Use))
1929 llvm_unreachable("Null def but use not point to live on entry def");
1930 } else if (std::find(Def->user_begin(), Def->user_end(), Use) ==
1931 Def->user_end()) {
1932 llvm_unreachable("Did not find use in def's use list");
1933 }
1934}
1935
1936/// \brief Verify the immediate use information, by walking all the memory
1937/// accesses and verifying that, for each use, it appears in the
1938/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001939void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001940 for (BasicBlock &B : F) {
1941 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00001942 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00001943 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
1944 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00001945 "Incomplete MemoryPhi Node");
George Burgess IVe1100f52016-02-02 22:46:49 +00001946 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1947 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Daniel Berlin14300262016-06-21 18:39:20 +00001948 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001949
1950 for (Instruction &I : B) {
1951 if (MemoryAccess *MA = getMemoryAccess(&I)) {
1952 assert(isa<MemoryUseOrDef>(MA) &&
1953 "Found a phi node not attached to a bb");
1954 verifyUseInDefs(cast<MemoryUseOrDef>(MA)->getDefiningAccess(), MA);
1955 }
1956 }
1957 }
1958}
1959
1960MemoryAccess *MemorySSA::getMemoryAccess(const Value *I) const {
Daniel Berlinf6c9ae92016-02-10 17:41:25 +00001961 return ValueToMemoryAccess.lookup(I);
George Burgess IVe1100f52016-02-02 22:46:49 +00001962}
1963
1964MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
1965 return cast_or_null<MemoryPhi>(getMemoryAccess((const Value *)BB));
1966}
1967
Daniel Berlin5c46b942016-07-19 22:49:43 +00001968/// Perform a local numbering on blocks so that instruction ordering can be
1969/// determined in constant time.
1970/// TODO: We currently just number in order. If we numbered by N, we could
1971/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
1972/// log2(N) sequences of mixed before and after) without needing to invalidate
1973/// the numbering.
1974void MemorySSA::renumberBlock(const BasicBlock *B) const {
1975 // The pre-increment ensures the numbers really start at 1.
1976 unsigned long CurrentNumber = 0;
1977 const AccessList *AL = getBlockAccesses(B);
1978 assert(AL != nullptr && "Asking to renumber an empty block");
1979 for (const auto &I : *AL)
1980 BlockNumbering[&I] = ++CurrentNumber;
1981 BlockNumberingValid.insert(B);
1982}
1983
George Burgess IVe1100f52016-02-02 22:46:49 +00001984/// \brief Determine, for two memory accesses in the same block,
1985/// whether \p Dominator dominates \p Dominatee.
1986/// \returns True if \p Dominator dominates \p Dominatee.
1987bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
1988 const MemoryAccess *Dominatee) const {
Sebastian Pope1f60b12016-06-10 21:36:41 +00001989
Daniel Berlin5c46b942016-07-19 22:49:43 +00001990 const BasicBlock *DominatorBlock = Dominator->getBlock();
Daniel Berlin5c46b942016-07-19 22:49:43 +00001991
Daniel Berlin19860302016-07-19 23:08:08 +00001992 assert((DominatorBlock == Dominatee->getBlock()) &&
Daniel Berlin5c46b942016-07-19 22:49:43 +00001993 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00001994 // A node dominates itself.
1995 if (Dominatee == Dominator)
1996 return true;
1997
1998 // When Dominatee is defined on function entry, it is not dominated by another
1999 // memory access.
2000 if (isLiveOnEntryDef(Dominatee))
2001 return false;
2002
2003 // When Dominator is defined on function entry, it dominates the other memory
2004 // access.
2005 if (isLiveOnEntryDef(Dominator))
2006 return true;
2007
Daniel Berlin5c46b942016-07-19 22:49:43 +00002008 if (!BlockNumberingValid.count(DominatorBlock))
2009 renumberBlock(DominatorBlock);
George Burgess IVe1100f52016-02-02 22:46:49 +00002010
Daniel Berlin5c46b942016-07-19 22:49:43 +00002011 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
2012 // All numbers start with 1
2013 assert(DominatorNum != 0 && "Block was not numbered properly");
2014 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
2015 assert(DominateeNum != 0 && "Block was not numbered properly");
2016 return DominatorNum < DominateeNum;
George Burgess IVe1100f52016-02-02 22:46:49 +00002017}
2018
George Burgess IV5f308972016-07-19 01:29:15 +00002019bool MemorySSA::dominates(const MemoryAccess *Dominator,
2020 const MemoryAccess *Dominatee) const {
2021 if (Dominator == Dominatee)
2022 return true;
2023
2024 if (isLiveOnEntryDef(Dominatee))
2025 return false;
2026
2027 if (Dominator->getBlock() != Dominatee->getBlock())
2028 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
2029 return locallyDominates(Dominator, Dominatee);
2030}
2031
George Burgess IVe1100f52016-02-02 22:46:49 +00002032const static char LiveOnEntryStr[] = "liveOnEntry";
2033
2034void MemoryDef::print(raw_ostream &OS) const {
2035 MemoryAccess *UO = getDefiningAccess();
2036
2037 OS << getID() << " = MemoryDef(";
2038 if (UO && UO->getID())
2039 OS << UO->getID();
2040 else
2041 OS << LiveOnEntryStr;
2042 OS << ')';
2043}
2044
2045void MemoryPhi::print(raw_ostream &OS) const {
2046 bool First = true;
2047 OS << getID() << " = MemoryPhi(";
2048 for (const auto &Op : operands()) {
2049 BasicBlock *BB = getIncomingBlock(Op);
2050 MemoryAccess *MA = cast<MemoryAccess>(Op);
2051 if (!First)
2052 OS << ',';
2053 else
2054 First = false;
2055
2056 OS << '{';
2057 if (BB->hasName())
2058 OS << BB->getName();
2059 else
2060 BB->printAsOperand(OS, false);
2061 OS << ',';
2062 if (unsigned ID = MA->getID())
2063 OS << ID;
2064 else
2065 OS << LiveOnEntryStr;
2066 OS << '}';
2067 }
2068 OS << ')';
2069}
2070
2071MemoryAccess::~MemoryAccess() {}
2072
2073void MemoryUse::print(raw_ostream &OS) const {
2074 MemoryAccess *UO = getDefiningAccess();
2075 OS << "MemoryUse(";
2076 if (UO && UO->getID())
2077 OS << UO->getID();
2078 else
2079 OS << LiveOnEntryStr;
2080 OS << ')';
2081}
2082
2083void MemoryAccess::dump() const {
2084 print(dbgs());
2085 dbgs() << "\n";
2086}
2087
Chad Rosier232e29e2016-07-06 21:20:47 +00002088char MemorySSAPrinterLegacyPass::ID = 0;
2089
2090MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
2091 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
2092}
2093
2094void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
2095 AU.setPreservesAll();
2096 AU.addRequired<MemorySSAWrapperPass>();
2097 AU.addPreserved<MemorySSAWrapperPass>();
2098}
2099
2100bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
2101 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2102 MSSA.print(dbgs());
2103 if (VerifyMemorySSA)
2104 MSSA.verifyMemorySSA();
2105 return false;
2106}
2107
Geoff Berryb96d3b22016-06-01 21:30:40 +00002108char MemorySSAAnalysis::PassID;
George Burgess IVe1100f52016-02-02 22:46:49 +00002109
Geoff Berryb96d3b22016-06-01 21:30:40 +00002110MemorySSA MemorySSAAnalysis::run(Function &F, AnalysisManager<Function> &AM) {
2111 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2112 auto &AA = AM.getResult<AAManager>(F);
2113 return MemorySSA(F, &AA, &DT);
George Burgess IVe1100f52016-02-02 22:46:49 +00002114}
2115
Geoff Berryb96d3b22016-06-01 21:30:40 +00002116PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
2117 FunctionAnalysisManager &AM) {
2118 OS << "MemorySSA for function: " << F.getName() << "\n";
2119 AM.getResult<MemorySSAAnalysis>(F).print(OS);
2120
2121 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00002122}
2123
Geoff Berryb96d3b22016-06-01 21:30:40 +00002124PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
2125 FunctionAnalysisManager &AM) {
2126 AM.getResult<MemorySSAAnalysis>(F).verifyMemorySSA();
2127
2128 return PreservedAnalyses::all();
2129}
2130
2131char MemorySSAWrapperPass::ID = 0;
2132
2133MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
2134 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
2135}
2136
2137void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
2138
2139void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002140 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002141 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
2142 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00002143}
2144
Geoff Berryb96d3b22016-06-01 21:30:40 +00002145bool MemorySSAWrapperPass::runOnFunction(Function &F) {
2146 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2147 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2148 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002149 return false;
2150}
2151
Geoff Berryb96d3b22016-06-01 21:30:40 +00002152void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00002153
Geoff Berryb96d3b22016-06-01 21:30:40 +00002154void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002155 MSSA->print(OS);
2156}
2157
George Burgess IVe1100f52016-02-02 22:46:49 +00002158MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
2159
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002160MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A,
2161 DominatorTree *D)
Daniel Berlin5c46b942016-07-19 22:49:43 +00002162 : MemorySSAWalker(M), Walker(*M, *A, *D, Cache), AutoResetWalker(true) {}
George Burgess IVe1100f52016-02-02 22:46:49 +00002163
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002164MemorySSA::CachingWalker::~CachingWalker() {}
George Burgess IVe1100f52016-02-02 22:46:49 +00002165
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002166void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) {
Daniel Berlin83fc77b2016-03-01 18:46:54 +00002167 // TODO: We can do much better cache invalidation with differently stored
2168 // caches. For now, for MemoryUses, we simply remove them
2169 // from the cache, and kill the entire call/non-call cache for everything
2170 // else. The problem is for phis or defs, currently we'd need to follow use
2171 // chains down and invalidate anything below us in the chain that currently
2172 // terminates at this access.
2173
2174 // See if this is a MemoryUse, if so, just remove the cached info. MemoryUse
2175 // is by definition never a barrier, so nothing in the cache could point to
2176 // this use. In that case, we only need invalidate the info for the use
2177 // itself.
2178
2179 if (MemoryUse *MU = dyn_cast<MemoryUse>(MA)) {
George Burgess IV5f308972016-07-19 01:29:15 +00002180 UpwardsMemoryQuery Q(MU->getMemoryInst(), MU);
2181 Cache.remove(MU, Q.StartingLoc, Q.IsCall);
Geoff Berry9fe26e62016-04-22 14:44:10 +00002182 } else {
2183 // 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 +00002184 Cache.clear();
Geoff Berry9fe26e62016-04-22 14:44:10 +00002185 }
2186
Filipe Cabecinhas0da99372016-04-29 15:22:48 +00002187#ifdef EXPENSIVE_CHECKS
Geoff Berry9fe26e62016-04-22 14:44:10 +00002188 verifyRemoved(MA);
2189#endif
Daniel Berlin83fc77b2016-03-01 18:46:54 +00002190}
2191
George Burgess IVe1100f52016-02-02 22:46:49 +00002192/// \brief Walk the use-def chains starting at \p MA and find
2193/// the MemoryAccess that actually clobbers Loc.
2194///
2195/// \returns our clobbering memory access
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002196MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
2197 MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +00002198 MemoryAccess *New = Walker.findClobber(StartingAccess, Q);
2199#ifdef EXPENSIVE_CHECKS
2200 MemoryAccess *NewNoCache =
2201 Walker.findClobber(StartingAccess, Q, /*UseWalkerCache=*/false);
2202 assert(NewNoCache == New && "Cache made us hand back a different result?");
2203#endif
2204 if (AutoResetWalker)
2205 resetClobberWalker();
2206 return New;
George Burgess IVe1100f52016-02-02 22:46:49 +00002207}
2208
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002209MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
2210 MemoryAccess *StartingAccess, MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002211 if (isa<MemoryPhi>(StartingAccess))
2212 return StartingAccess;
2213
2214 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
2215 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
2216 return StartingUseOrDef;
2217
2218 Instruction *I = StartingUseOrDef->getMemoryInst();
2219
2220 // Conservatively, fences are always clobbers, so don't perform the walk if we
2221 // hit a fence.
David Majnemera940f362016-07-15 17:19:24 +00002222 if (!ImmutableCallSite(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002223 return StartingUseOrDef;
2224
2225 UpwardsMemoryQuery Q;
2226 Q.OriginalAccess = StartingUseOrDef;
2227 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00002228 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00002229 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00002230
George Burgess IV5f308972016-07-19 01:29:15 +00002231 if (auto *CacheResult = Cache.lookup(StartingUseOrDef, Loc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00002232 return CacheResult;
2233
2234 // Unlike the other function, do not walk to the def of a def, because we are
2235 // handed something we already believe is the clobbering access.
2236 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
2237 ? StartingUseOrDef->getDefiningAccess()
2238 : StartingUseOrDef;
2239
2240 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002241 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2242 DEBUG(dbgs() << *StartingUseOrDef << "\n");
2243 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2244 DEBUG(dbgs() << *Clobber << "\n");
2245 return Clobber;
2246}
2247
2248MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002249MemorySSA::CachingWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
2250 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2251 // If this is a MemoryPhi, we can't do anything.
2252 if (!StartingAccess)
2253 return MA;
George Burgess IVe1100f52016-02-02 22:46:49 +00002254
George Burgess IV400ae402016-07-20 19:51:34 +00002255 const Instruction *I = StartingAccess->getMemoryInst();
George Burgess IV5f308972016-07-19 01:29:15 +00002256 UpwardsMemoryQuery Q(I, StartingAccess);
David Majnemera940f362016-07-15 17:19:24 +00002257 // We can't sanely do anything with a fences, they conservatively
George Burgess IVe1100f52016-02-02 22:46:49 +00002258 // clobber all memory, and have no locations to get pointers from to
David Majnemera940f362016-07-15 17:19:24 +00002259 // try to disambiguate.
George Burgess IV5f308972016-07-19 01:29:15 +00002260 if (!Q.IsCall && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002261 return StartingAccess;
2262
George Burgess IV5f308972016-07-19 01:29:15 +00002263 if (auto *CacheResult = Cache.lookup(StartingAccess, Q.StartingLoc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00002264 return CacheResult;
2265
George Burgess IV024f3d22016-08-03 19:57:02 +00002266 if (isUseTriviallyOptimizableToLiveOnEntry(*MSSA->AA, I)) {
2267 MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
2268 Cache.insert(StartingAccess, LiveOnEntry, Q.StartingLoc, Q.IsCall);
2269 return LiveOnEntry;
2270 }
2271
George Burgess IVe1100f52016-02-02 22:46:49 +00002272 // Start with the thing we already think clobbers this location
2273 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2274
2275 // At this point, DefiningAccess may be the live on entry def.
2276 // If it is, we will not get a better result.
2277 if (MSSA->isLiveOnEntryDef(DefiningAccess))
2278 return DefiningAccess;
2279
2280 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002281 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2282 DEBUG(dbgs() << *DefiningAccess << "\n");
2283 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2284 DEBUG(dbgs() << *Result << "\n");
2285
2286 return Result;
2287}
2288
Geoff Berry9fe26e62016-04-22 14:44:10 +00002289// Verify that MA doesn't exist in any of the caches.
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002290void MemorySSA::CachingWalker::verifyRemoved(MemoryAccess *MA) {
George Burgess IV5f308972016-07-19 01:29:15 +00002291 assert(!Cache.contains(MA) && "Found removed MemoryAccess in cache.");
Geoff Berry9fe26e62016-04-22 14:44:10 +00002292}
2293
George Burgess IVe1100f52016-02-02 22:46:49 +00002294MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002295DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002296 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2297 return Use->getDefiningAccess();
2298 return MA;
2299}
2300
2301MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
2302 MemoryAccess *StartingAccess, MemoryLocation &) {
2303 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2304 return Use->getDefiningAccess();
2305 return StartingAccess;
2306}
George Burgess IV5f308972016-07-19 01:29:15 +00002307} // namespace llvm