blob: b02a3f55d03bd6669f93f0ab9b800c17b9e8c841 [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()) {}
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000108 MemoryLocOrCall(const MemoryUseOrDef *MUD)
109 : MemoryLocOrCall(MUD->getMemoryInst()) {}
Daniel Berlindff31de2016-08-02 21:57:52 +0000110
111 MemoryLocOrCall(Instruction *Inst) {
112 if (ImmutableCallSite(Inst)) {
113 IsCall = true;
114 CS = ImmutableCallSite(Inst);
115 } else {
116 IsCall = false;
117 // There is no such thing as a memorylocation for a fence inst, and it is
118 // unique in that regard.
119 if (!isa<FenceInst>(Inst))
120 Loc = MemoryLocation::get(Inst);
121 }
122 }
123
124 explicit MemoryLocOrCall(const MemoryLocation &Loc)
125 : IsCall(false), Loc(Loc) {}
126
127 bool IsCall;
128 ImmutableCallSite getCS() const {
129 assert(IsCall);
130 return CS;
131 }
132 MemoryLocation getLoc() const {
133 assert(!IsCall);
134 return Loc;
135 }
136
137 bool operator==(const MemoryLocOrCall &Other) const {
138 if (IsCall != Other.IsCall)
139 return false;
140
141 if (IsCall)
142 return CS.getCalledValue() == Other.CS.getCalledValue();
143 return Loc == Other.Loc;
144 }
145
146private:
147 // FIXME: MSVC 2013 does not properly implement C++11 union rules, once we
148 // require newer versions, this should be made an anonymous union again.
149 ImmutableCallSite CS;
150 MemoryLocation Loc;
151};
152}
153
154namespace llvm {
155template <> struct DenseMapInfo<MemoryLocOrCall> {
156 static inline MemoryLocOrCall getEmptyKey() {
157 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getEmptyKey());
158 }
159 static inline MemoryLocOrCall getTombstoneKey() {
160 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getTombstoneKey());
161 }
162 static unsigned getHashValue(const MemoryLocOrCall &MLOC) {
163 if (MLOC.IsCall)
164 return hash_combine(MLOC.IsCall,
165 DenseMapInfo<const Value *>::getHashValue(
166 MLOC.getCS().getCalledValue()));
167 return hash_combine(
168 MLOC.IsCall, DenseMapInfo<MemoryLocation>::getHashValue(MLOC.getLoc()));
169 }
170 static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS) {
171 return LHS == RHS;
172 }
173};
Daniel Berlindf101192016-08-03 00:01:46 +0000174
George Burgess IVf7672852016-08-03 19:59:11 +0000175enum class Reorderability { Always, IfNoAlias, Never };
George Burgess IV82e355c2016-08-03 19:39:54 +0000176
177/// This does one-way checks to see if Use could theoretically be hoisted above
178/// MayClobber. This will not check the other way around.
179///
180/// This assumes that, for the purposes of MemorySSA, Use comes directly after
181/// MayClobber, with no potentially clobbering operations in between them.
182/// (Where potentially clobbering ops are memory barriers, aliased stores, etc.)
183static Reorderability getLoadReorderability(const LoadInst *Use,
184 const LoadInst *MayClobber) {
185 bool VolatileUse = Use->isVolatile();
186 bool VolatileClobber = MayClobber->isVolatile();
187 // Volatile operations may never be reordered with other volatile operations.
188 if (VolatileUse && VolatileClobber)
189 return Reorderability::Never;
190
191 // The lang ref allows reordering of volatile and non-volatile operations.
192 // Whether an aliasing nonvolatile load and volatile load can be reordered,
193 // though, is ambiguous. Because it may not be best to exploit this ambiguity,
194 // we only allow volatile/non-volatile reordering if the volatile and
195 // non-volatile operations don't alias.
196 Reorderability Result = VolatileUse || VolatileClobber
197 ? Reorderability::IfNoAlias
198 : Reorderability::Always;
199
200 // If a load is seq_cst, it cannot be moved above other loads. If its ordering
201 // is weaker, it can be moved above other loads. We just need to be sure that
202 // MayClobber isn't an acquire load, because loads can't be moved above
203 // acquire loads.
204 //
205 // Note that this explicitly *does* allow the free reordering of monotonic (or
206 // weaker) loads of the same address.
207 bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent;
208 bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(),
209 AtomicOrdering::Acquire);
210 if (SeqCstUse || MayClobberIsAcquire)
211 return Reorderability::Never;
212 return Result;
213}
214
Sebastian Popd57d93c2016-10-12 03:08:40 +0000215static bool instructionClobbersQuery(MemoryDef *MD,
216 const MemoryLocation &UseLoc,
217 const Instruction *UseInst,
218 AliasAnalysis &AA) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000219 Instruction *DefInst = MD->getMemoryInst();
220 assert(DefInst && "Defining instruction not actually an instruction");
George Burgess IV5f308972016-07-19 01:29:15 +0000221
Daniel Berlindf101192016-08-03 00:01:46 +0000222 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
223 // These intrinsics will show up as affecting memory, but they are just
224 // markers.
225 switch (II->getIntrinsicID()) {
226 case Intrinsic::lifetime_start:
227 case Intrinsic::lifetime_end:
228 case Intrinsic::invariant_start:
229 case Intrinsic::invariant_end:
230 case Intrinsic::assume:
231 return false;
232 default:
233 break;
234 }
235 }
236
Daniel Berlindff31de2016-08-02 21:57:52 +0000237 ImmutableCallSite UseCS(UseInst);
238 if (UseCS) {
239 ModRefInfo I = AA.getModRefInfo(DefInst, UseCS);
240 return I != MRI_NoModRef;
241 }
George Burgess IV82e355c2016-08-03 19:39:54 +0000242
243 if (auto *DefLoad = dyn_cast<LoadInst>(DefInst)) {
244 if (auto *UseLoad = dyn_cast<LoadInst>(UseInst)) {
245 switch (getLoadReorderability(UseLoad, DefLoad)) {
246 case Reorderability::Always:
247 return false;
248 case Reorderability::Never:
249 return true;
250 case Reorderability::IfNoAlias:
251 return !AA.isNoAlias(UseLoc, MemoryLocation::get(DefLoad));
252 }
253 }
254 }
255
Daniel Berlindff31de2016-08-02 21:57:52 +0000256 return AA.getModRefInfo(DefInst, UseLoc) & MRI_Mod;
257}
258
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000259static bool instructionClobbersQuery(MemoryDef *MD, const MemoryUseOrDef *MU,
260 const MemoryLocOrCall &UseMLOC,
261 AliasAnalysis &AA) {
262 // FIXME: This is a temporary hack to allow a single instructionClobbersQuery
263 // to exist while MemoryLocOrCall is pushed through places.
264 if (UseMLOC.IsCall)
265 return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(),
266 AA);
267 return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(),
268 AA);
269}
270
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000271// Return true when MD may alias MU, return false otherwise.
272bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
273 AliasAnalysis &AA) {
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000274 return instructionClobbersQuery(MD, MU, MemoryLocOrCall(MU), AA);
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000275}
276}
277
278namespace {
279struct UpwardsMemoryQuery {
280 // True if our original query started off as a call
281 bool IsCall;
282 // The pointer location we started the query with. This will be empty if
283 // IsCall is true.
284 MemoryLocation StartingLoc;
285 // This is the instruction we were querying about.
286 const Instruction *Inst;
287 // The MemoryAccess we actually got called with, used to test local domination
288 const MemoryAccess *OriginalAccess;
289
290 UpwardsMemoryQuery()
291 : IsCall(false), Inst(nullptr), OriginalAccess(nullptr) {}
292
293 UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
294 : IsCall(ImmutableCallSite(Inst)), Inst(Inst), OriginalAccess(Access) {
295 if (!IsCall)
296 StartingLoc = MemoryLocation::get(Inst);
297 }
298};
299
300static bool lifetimeEndsAt(MemoryDef *MD, const MemoryLocation &Loc,
301 AliasAnalysis &AA) {
302 Instruction *Inst = MD->getMemoryInst();
303 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
304 switch (II->getIntrinsicID()) {
305 case Intrinsic::lifetime_start:
306 case Intrinsic::lifetime_end:
307 return AA.isMustAlias(MemoryLocation(II->getArgOperand(1)), Loc);
308 default:
309 return false;
310 }
311 }
312 return false;
313}
314
315static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysis &AA,
316 const Instruction *I) {
317 // If the memory can't be changed, then loads of the memory can't be
318 // clobbered.
319 //
320 // FIXME: We should handle invariant groups, as well. It's a bit harder,
321 // because we need to pay close attention to invariant group barriers.
322 return isa<LoadInst>(I) && (I->getMetadata(LLVMContext::MD_invariant_load) ||
323 AA.pointsToConstantMemory(I));
324}
325
George Burgess IV5f308972016-07-19 01:29:15 +0000326/// Cache for our caching MemorySSA walker.
327class WalkerCache {
328 DenseMap<ConstMemoryAccessPair, MemoryAccess *> Accesses;
329 DenseMap<const MemoryAccess *, MemoryAccess *> Calls;
330
331public:
332 MemoryAccess *lookup(const MemoryAccess *MA, const MemoryLocation &Loc,
333 bool IsCall) const {
334 ++NumClobberCacheLookups;
335 MemoryAccess *R = IsCall ? Calls.lookup(MA) : Accesses.lookup({MA, Loc});
336 if (R)
337 ++NumClobberCacheHits;
338 return R;
339 }
340
341 bool insert(const MemoryAccess *MA, MemoryAccess *To,
342 const MemoryLocation &Loc, bool IsCall) {
343 // This is fine for Phis, since there are times where we can't optimize
344 // them. Making a def its own clobber is never correct, though.
345 assert((MA != To || isa<MemoryPhi>(MA)) &&
346 "Something can't clobber itself!");
347
348 ++NumClobberCacheInserts;
349 bool Inserted;
350 if (IsCall)
351 Inserted = Calls.insert({MA, To}).second;
352 else
353 Inserted = Accesses.insert({{MA, Loc}, To}).second;
354
355 return Inserted;
356 }
357
358 bool remove(const MemoryAccess *MA, const MemoryLocation &Loc, bool IsCall) {
359 return IsCall ? Calls.erase(MA) : Accesses.erase({MA, Loc});
360 }
361
362 void clear() {
363 Accesses.clear();
364 Calls.clear();
365 }
366
367 bool contains(const MemoryAccess *MA) const {
368 for (auto &P : Accesses)
369 if (P.first.first == MA || P.second == MA)
370 return true;
371 for (auto &P : Calls)
372 if (P.first == MA || P.second == MA)
373 return true;
374 return false;
375 }
376};
377
378/// Walks the defining uses of MemoryDefs. Stops after we hit something that has
379/// no defining use (e.g. a MemoryPhi or liveOnEntry). Note that, when comparing
380/// against a null def_chain_iterator, this will compare equal only after
381/// walking said Phi/liveOnEntry.
382struct def_chain_iterator
383 : public iterator_facade_base<def_chain_iterator, std::forward_iterator_tag,
384 MemoryAccess *> {
385 def_chain_iterator() : MA(nullptr) {}
386 def_chain_iterator(MemoryAccess *MA) : MA(MA) {}
387
388 MemoryAccess *operator*() const { return MA; }
389
390 def_chain_iterator &operator++() {
391 // N.B. liveOnEntry has a null defining access.
392 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
393 MA = MUD->getDefiningAccess();
394 else
395 MA = nullptr;
396 return *this;
397 }
398
399 bool operator==(const def_chain_iterator &O) const { return MA == O.MA; }
400
401private:
402 MemoryAccess *MA;
403};
404
405static iterator_range<def_chain_iterator>
406def_chain(MemoryAccess *MA, MemoryAccess *UpTo = nullptr) {
407#ifdef EXPENSIVE_CHECKS
408 assert((!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator()) &&
409 "UpTo isn't in the def chain!");
410#endif
411 return make_range(def_chain_iterator(MA), def_chain_iterator(UpTo));
412}
413
414/// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
415/// inbetween `Start` and `ClobberAt` can clobbers `Start`.
416///
417/// This is meant to be as simple and self-contained as possible. Because it
418/// uses no cache, etc., it can be relatively expensive.
419///
420/// \param Start The MemoryAccess that we want to walk from.
421/// \param ClobberAt A clobber for Start.
422/// \param StartLoc The MemoryLocation for Start.
423/// \param MSSA The MemorySSA isntance that Start and ClobberAt belong to.
424/// \param Query The UpwardsMemoryQuery we used for our search.
425/// \param AA The AliasAnalysis we used for our search.
426static void LLVM_ATTRIBUTE_UNUSED
427checkClobberSanity(MemoryAccess *Start, MemoryAccess *ClobberAt,
428 const MemoryLocation &StartLoc, const MemorySSA &MSSA,
429 const UpwardsMemoryQuery &Query, AliasAnalysis &AA) {
430 assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
431
432 if (MSSA.isLiveOnEntryDef(Start)) {
433 assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
434 "liveOnEntry must clobber itself");
435 return;
436 }
437
George Burgess IV5f308972016-07-19 01:29:15 +0000438 bool FoundClobber = false;
439 DenseSet<MemoryAccessPair> VisitedPhis;
440 SmallVector<MemoryAccessPair, 8> Worklist;
441 Worklist.emplace_back(Start, StartLoc);
442 // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
443 // is found, complain.
444 while (!Worklist.empty()) {
445 MemoryAccessPair MAP = Worklist.pop_back_val();
446 // All we care about is that nothing from Start to ClobberAt clobbers Start.
447 // We learn nothing from revisiting nodes.
448 if (!VisitedPhis.insert(MAP).second)
449 continue;
450
451 for (MemoryAccess *MA : def_chain(MAP.first)) {
452 if (MA == ClobberAt) {
453 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
454 // instructionClobbersQuery isn't essentially free, so don't use `|=`,
455 // since it won't let us short-circuit.
456 //
457 // Also, note that this can't be hoisted out of the `Worklist` loop,
458 // since MD may only act as a clobber for 1 of N MemoryLocations.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000459 FoundClobber =
460 FoundClobber || MSSA.isLiveOnEntryDef(MD) ||
461 instructionClobbersQuery(MD, MAP.second, Query.Inst, AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000462 }
463 break;
464 }
465
466 // We should never hit liveOnEntry, unless it's the clobber.
467 assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
468
469 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
470 (void)MD;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000471 assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA) &&
George Burgess IV5f308972016-07-19 01:29:15 +0000472 "Found clobber before reaching ClobberAt!");
473 continue;
474 }
475
476 assert(isa<MemoryPhi>(MA));
477 Worklist.append(upward_defs_begin({MA, MAP.second}), upward_defs_end());
478 }
479 }
480
481 // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
482 // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
483 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
484 "ClobberAt never acted as a clobber");
485}
486
487/// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
488/// in one class.
489class ClobberWalker {
490 /// Save a few bytes by using unsigned instead of size_t.
491 using ListIndex = unsigned;
492
493 /// Represents a span of contiguous MemoryDefs, potentially ending in a
494 /// MemoryPhi.
495 struct DefPath {
496 MemoryLocation Loc;
497 // Note that, because we always walk in reverse, Last will always dominate
498 // First. Also note that First and Last are inclusive.
499 MemoryAccess *First;
500 MemoryAccess *Last;
George Burgess IV5f308972016-07-19 01:29:15 +0000501 Optional<ListIndex> Previous;
502
503 DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
504 Optional<ListIndex> Previous)
505 : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
506
507 DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
508 Optional<ListIndex> Previous)
509 : DefPath(Loc, Init, Init, Previous) {}
510 };
511
512 const MemorySSA &MSSA;
513 AliasAnalysis &AA;
514 DominatorTree &DT;
515 WalkerCache &WC;
516 UpwardsMemoryQuery *Query;
517 bool UseCache;
518
519 // Phi optimization bookkeeping
520 SmallVector<DefPath, 32> Paths;
521 DenseSet<ConstMemoryAccessPair> VisitedPhis;
522 DenseMap<const BasicBlock *, MemoryAccess *> WalkTargetCache;
523
524 void setUseCache(bool Use) { UseCache = Use; }
525 bool shouldIgnoreCache() const {
526 // UseCache will only be false when we're debugging, or when expensive
527 // checks are enabled. In either case, we don't care deeply about speed.
528 return LLVM_UNLIKELY(!UseCache);
529 }
530
531 void addCacheEntry(const MemoryAccess *What, MemoryAccess *To,
532 const MemoryLocation &Loc) const {
Daniel Berlin5c46b942016-07-19 22:49:43 +0000533// EXPENSIVE_CHECKS because most of these queries are redundant.
George Burgess IV5f308972016-07-19 01:29:15 +0000534#ifdef EXPENSIVE_CHECKS
535 assert(MSSA.dominates(To, What));
536#endif
537 if (shouldIgnoreCache())
538 return;
539 WC.insert(What, To, Loc, Query->IsCall);
540 }
541
542 MemoryAccess *lookupCache(const MemoryAccess *MA, const MemoryLocation &Loc) {
543 return shouldIgnoreCache() ? nullptr : WC.lookup(MA, Loc, Query->IsCall);
544 }
545
546 void cacheDefPath(const DefPath &DN, MemoryAccess *Target) const {
547 if (shouldIgnoreCache())
548 return;
549
550 for (MemoryAccess *MA : def_chain(DN.First, DN.Last))
551 addCacheEntry(MA, Target, DN.Loc);
552
553 // DefPaths only express the path we walked. So, DN.Last could either be a
554 // thing we want to cache, or not.
555 if (DN.Last != Target)
556 addCacheEntry(DN.Last, Target, DN.Loc);
557 }
558
559 /// Find the nearest def or phi that `From` can legally be optimized to.
560 ///
561 /// FIXME: Deduplicate this with MSSA::findDominatingDef. Ideally, MSSA should
562 /// keep track of this information for us, and allow us O(1) lookups of this
563 /// info.
564 MemoryAccess *getWalkTarget(const MemoryPhi *From) {
George Burgess IV5f308972016-07-19 01:29:15 +0000565 assert(From->getNumOperands() && "Phi with no operands?");
566
567 BasicBlock *BB = From->getBlock();
568 auto At = WalkTargetCache.find(BB);
569 if (At != WalkTargetCache.end())
570 return At->second;
571
572 SmallVector<const BasicBlock *, 8> ToCache;
573 ToCache.push_back(BB);
574
575 MemoryAccess *Result = MSSA.getLiveOnEntryDef();
576 DomTreeNode *Node = DT.getNode(BB);
577 while ((Node = Node->getIDom())) {
578 auto At = WalkTargetCache.find(BB);
579 if (At != WalkTargetCache.end()) {
580 Result = At->second;
581 break;
582 }
583
584 auto *Accesses = MSSA.getBlockAccesses(Node->getBlock());
585 if (Accesses) {
586 auto Iter = find_if(reverse(*Accesses), [](const MemoryAccess &MA) {
587 return !isa<MemoryUse>(MA);
588 });
589 if (Iter != Accesses->rend()) {
590 Result = const_cast<MemoryAccess *>(&*Iter);
591 break;
592 }
593 }
594
595 ToCache.push_back(Node->getBlock());
596 }
597
598 for (const BasicBlock *BB : ToCache)
599 WalkTargetCache.insert({BB, Result});
600 return Result;
601 }
602
603 /// Result of calling walkToPhiOrClobber.
604 struct UpwardsWalkResult {
605 /// The "Result" of the walk. Either a clobber, the last thing we walked, or
606 /// both.
607 MemoryAccess *Result;
608 bool IsKnownClobber;
609 bool FromCache;
610 };
611
612 /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
613 /// This will update Desc.Last as it walks. It will (optionally) also stop at
614 /// StopAt.
615 ///
616 /// This does not test for whether StopAt is a clobber
617 UpwardsWalkResult walkToPhiOrClobber(DefPath &Desc,
618 MemoryAccess *StopAt = nullptr) {
619 assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
620
621 for (MemoryAccess *Current : def_chain(Desc.Last)) {
622 Desc.Last = Current;
623 if (Current == StopAt)
624 return {Current, false, false};
625
626 if (auto *MD = dyn_cast<MemoryDef>(Current))
627 if (MSSA.isLiveOnEntryDef(MD) ||
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000628 instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA))
George Burgess IV5f308972016-07-19 01:29:15 +0000629 return {MD, true, false};
630
631 // Cache checks must be done last, because if Current is a clobber, the
632 // cache will contain the clobber for Current.
633 if (MemoryAccess *MA = lookupCache(Current, Desc.Loc))
634 return {MA, true, true};
635 }
636
637 assert(isa<MemoryPhi>(Desc.Last) &&
638 "Ended at a non-clobber that's not a phi?");
639 return {Desc.Last, false, false};
640 }
641
642 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
643 ListIndex PriorNode) {
644 auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),
645 upward_defs_end());
646 for (const MemoryAccessPair &P : UpwardDefs) {
647 PausedSearches.push_back(Paths.size());
648 Paths.emplace_back(P.second, P.first, PriorNode);
649 }
650 }
651
652 /// Represents a search that terminated after finding a clobber. This clobber
653 /// may or may not be present in the path of defs from LastNode..SearchStart,
654 /// since it may have been retrieved from cache.
655 struct TerminatedPath {
656 MemoryAccess *Clobber;
657 ListIndex LastNode;
658 };
659
660 /// Get an access that keeps us from optimizing to the given phi.
661 ///
662 /// PausedSearches is an array of indices into the Paths array. Its incoming
663 /// value is the indices of searches that stopped at the last phi optimization
664 /// target. It's left in an unspecified state.
665 ///
666 /// If this returns None, NewPaused is a vector of searches that terminated
667 /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
George Burgess IV14633b52016-08-03 01:22:19 +0000668 Optional<TerminatedPath>
George Burgess IV5f308972016-07-19 01:29:15 +0000669 getBlockingAccess(MemoryAccess *StopWhere,
670 SmallVectorImpl<ListIndex> &PausedSearches,
671 SmallVectorImpl<ListIndex> &NewPaused,
672 SmallVectorImpl<TerminatedPath> &Terminated) {
673 assert(!PausedSearches.empty() && "No searches to continue?");
674
675 // BFS vs DFS really doesn't make a difference here, so just do a DFS with
676 // PausedSearches as our stack.
677 while (!PausedSearches.empty()) {
678 ListIndex PathIndex = PausedSearches.pop_back_val();
679 DefPath &Node = Paths[PathIndex];
680
681 // If we've already visited this path with this MemoryLocation, we don't
682 // need to do so again.
683 //
684 // NOTE: That we just drop these paths on the ground makes caching
685 // behavior sporadic. e.g. given a diamond:
686 // A
687 // B C
688 // D
689 //
690 // ...If we walk D, B, A, C, we'll only cache the result of phi
691 // optimization for A, B, and D; C will be skipped because it dies here.
692 // This arguably isn't the worst thing ever, since:
693 // - We generally query things in a top-down order, so if we got below D
694 // without needing cache entries for {C, MemLoc}, then chances are
695 // that those cache entries would end up ultimately unused.
696 // - We still cache things for A, so C only needs to walk up a bit.
697 // If this behavior becomes problematic, we can fix without a ton of extra
698 // work.
699 if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
700 continue;
701
702 UpwardsWalkResult Res = walkToPhiOrClobber(Node, /*StopAt=*/StopWhere);
703 if (Res.IsKnownClobber) {
704 assert(Res.Result != StopWhere || Res.FromCache);
705 // If this wasn't a cache hit, we hit a clobber when walking. That's a
706 // failure.
George Burgess IV14633b52016-08-03 01:22:19 +0000707 TerminatedPath Term{Res.Result, PathIndex};
George Burgess IV5f308972016-07-19 01:29:15 +0000708 if (!Res.FromCache || !MSSA.dominates(Res.Result, StopWhere))
George Burgess IV14633b52016-08-03 01:22:19 +0000709 return Term;
George Burgess IV5f308972016-07-19 01:29:15 +0000710
711 // Otherwise, it's a valid thing to potentially optimize to.
George Burgess IV14633b52016-08-03 01:22:19 +0000712 Terminated.push_back(Term);
George Burgess IV5f308972016-07-19 01:29:15 +0000713 continue;
714 }
715
716 if (Res.Result == StopWhere) {
717 // We've hit our target. Save this path off for if we want to continue
718 // walking.
719 NewPaused.push_back(PathIndex);
720 continue;
721 }
722
723 assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
724 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
725 }
726
727 return None;
728 }
729
730 template <typename T, typename Walker>
731 struct generic_def_path_iterator
732 : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
733 std::forward_iterator_tag, T *> {
734 generic_def_path_iterator() : W(nullptr), N(None) {}
735 generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
736
737 T &operator*() const { return curNode(); }
738
739 generic_def_path_iterator &operator++() {
740 N = curNode().Previous;
741 return *this;
742 }
743
744 bool operator==(const generic_def_path_iterator &O) const {
745 if (N.hasValue() != O.N.hasValue())
746 return false;
747 return !N.hasValue() || *N == *O.N;
748 }
749
750 private:
751 T &curNode() const { return W->Paths[*N]; }
752
753 Walker *W;
754 Optional<ListIndex> N;
755 };
756
757 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
758 using const_def_path_iterator =
759 generic_def_path_iterator<const DefPath, const ClobberWalker>;
760
761 iterator_range<def_path_iterator> def_path(ListIndex From) {
762 return make_range(def_path_iterator(this, From), def_path_iterator());
763 }
764
765 iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
766 return make_range(const_def_path_iterator(this, From),
767 const_def_path_iterator());
768 }
769
770 struct OptznResult {
771 /// The path that contains our result.
772 TerminatedPath PrimaryClobber;
773 /// The paths that we can legally cache back from, but that aren't
774 /// necessarily the result of the Phi optimization.
775 SmallVector<TerminatedPath, 4> OtherClobbers;
776 };
777
778 ListIndex defPathIndex(const DefPath &N) const {
779 // The assert looks nicer if we don't need to do &N
780 const DefPath *NP = &N;
781 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
782 "Out of bounds DefPath!");
783 return NP - &Paths.front();
784 }
785
786 /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
787 /// that act as legal clobbers. Note that this won't return *all* clobbers.
788 ///
789 /// Phi optimization algorithm tl;dr:
790 /// - Find the earliest def/phi, A, we can optimize to
791 /// - Find if all paths from the starting memory access ultimately reach A
792 /// - If not, optimization isn't possible.
793 /// - Otherwise, walk from A to another clobber or phi, A'.
794 /// - If A' is a def, we're done.
795 /// - If A' is a phi, try to optimize it.
796 ///
797 /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
798 /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
799 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
800 const MemoryLocation &Loc) {
801 assert(Paths.empty() && VisitedPhis.empty() &&
802 "Reset the optimization state.");
803
804 Paths.emplace_back(Loc, Start, Phi, None);
805 // Stores how many "valid" optimization nodes we had prior to calling
806 // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
807 auto PriorPathsSize = Paths.size();
808
809 SmallVector<ListIndex, 16> PausedSearches;
810 SmallVector<ListIndex, 8> NewPaused;
811 SmallVector<TerminatedPath, 4> TerminatedPaths;
812
813 addSearches(Phi, PausedSearches, 0);
814
815 // Moves the TerminatedPath with the "most dominated" Clobber to the end of
816 // Paths.
817 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
818 assert(!Paths.empty() && "Need a path to move");
George Burgess IV5f308972016-07-19 01:29:15 +0000819 auto Dom = Paths.begin();
820 for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
821 if (!MSSA.dominates(I->Clobber, Dom->Clobber))
822 Dom = I;
823 auto Last = Paths.end() - 1;
824 if (Last != Dom)
825 std::iter_swap(Last, Dom);
826 };
827
828 MemoryPhi *Current = Phi;
829 while (1) {
830 assert(!MSSA.isLiveOnEntryDef(Current) &&
831 "liveOnEntry wasn't treated as a clobber?");
832
833 MemoryAccess *Target = getWalkTarget(Current);
834 // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
835 // optimization for the prior phi.
836 assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
837 return MSSA.dominates(P.Clobber, Target);
838 }));
839
840 // FIXME: This is broken, because the Blocker may be reported to be
841 // liveOnEntry, and we'll happily wait for that to disappear (read: never)
George Burgess IV7f414b92016-08-22 23:40:01 +0000842 // For the moment, this is fine, since we do nothing with 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 IV5f308972016-07-19 01:29:15 +0000857
858 // Two things:
859 // A. We can't reliably cache all of NewPaused back. Consider a case
860 // where we have two paths in NewPaused; one of which can't optimize
861 // above this phi, whereas the other can. If we cache the second path
862 // back, we'll end up with suboptimal cache entries. We can handle
863 // cases like this a bit better when we either try to find all
864 // clobbers that block phi optimization, or when our cache starts
865 // supporting unfinished searches.
866 // B. We can't reliably cache TerminatedPaths back here without doing
867 // extra checks; consider a case like:
868 // T
869 // / \
870 // D C
871 // \ /
872 // S
873 // Where T is our target, C is a node with a clobber on it, D is a
874 // diamond (with a clobber *only* on the left or right node, N), and
875 // S is our start. Say we walk to D, through the node opposite N
876 // (read: ignoring the clobber), and see a cache entry in the top
877 // node of D. That cache entry gets put into TerminatedPaths. We then
878 // walk up to C (N is later in our worklist), find the clobber, and
879 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
880 // the bottom part of D to the cached clobber, ignoring the clobber
881 // in N. Again, this problem goes away if we start tracking all
882 // blockers for a given phi optimization.
883 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
884 return {Result, {}};
885 }
886
887 // If there's nothing left to search, then all paths led to valid clobbers
888 // that we got from our cache; pick the nearest to the start, and allow
889 // the rest to be cached back.
890 if (NewPaused.empty()) {
891 MoveDominatedPathToEnd(TerminatedPaths);
892 TerminatedPath Result = TerminatedPaths.pop_back_val();
893 return {Result, std::move(TerminatedPaths)};
894 }
895
896 MemoryAccess *DefChainEnd = nullptr;
897 SmallVector<TerminatedPath, 4> Clobbers;
898 for (ListIndex Paused : NewPaused) {
899 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
900 if (WR.IsKnownClobber)
901 Clobbers.push_back({WR.Result, Paused});
902 else
903 // Micro-opt: If we hit the end of the chain, save it.
904 DefChainEnd = WR.Result;
905 }
906
907 if (!TerminatedPaths.empty()) {
908 // If we couldn't find the dominating phi/liveOnEntry in the above loop,
909 // do it now.
910 if (!DefChainEnd)
911 for (MemoryAccess *MA : def_chain(Target))
912 DefChainEnd = MA;
913
914 // If any of the terminated paths don't dominate the phi we'll try to
915 // optimize, we need to figure out what they are and quit.
916 const BasicBlock *ChainBB = DefChainEnd->getBlock();
917 for (const TerminatedPath &TP : TerminatedPaths) {
918 // Because we know that DefChainEnd is as "high" as we can go, we
919 // don't need local dominance checks; BB dominance is sufficient.
920 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
921 Clobbers.push_back(TP);
922 }
923 }
924
925 // If we have clobbers in the def chain, find the one closest to Current
926 // and quit.
927 if (!Clobbers.empty()) {
928 MoveDominatedPathToEnd(Clobbers);
929 TerminatedPath Result = Clobbers.pop_back_val();
930 return {Result, std::move(Clobbers)};
931 }
932
933 assert(all_of(NewPaused,
934 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
935
936 // Because liveOnEntry is a clobber, this must be a phi.
937 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
938
939 PriorPathsSize = Paths.size();
940 PausedSearches.clear();
941 for (ListIndex I : NewPaused)
942 addSearches(DefChainPhi, PausedSearches, I);
943 NewPaused.clear();
944
945 Current = DefChainPhi;
946 }
947 }
948
949 /// Caches everything in an OptznResult.
950 void cacheOptResult(const OptznResult &R) {
951 if (R.OtherClobbers.empty()) {
952 // If we're not going to be caching OtherClobbers, don't bother with
953 // marking visited/etc.
954 for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode))
955 cacheDefPath(N, R.PrimaryClobber.Clobber);
956 return;
957 }
958
959 // PrimaryClobber is our answer. If we can cache anything back, we need to
960 // stop caching when we visit PrimaryClobber.
961 SmallBitVector Visited(Paths.size());
962 for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode)) {
963 Visited[defPathIndex(N)] = true;
964 cacheDefPath(N, R.PrimaryClobber.Clobber);
965 }
966
967 for (const TerminatedPath &P : R.OtherClobbers) {
968 for (const DefPath &N : const_def_path(P.LastNode)) {
969 ListIndex NIndex = defPathIndex(N);
970 if (Visited[NIndex])
971 break;
972 Visited[NIndex] = true;
973 cacheDefPath(N, P.Clobber);
974 }
975 }
976 }
977
978 void verifyOptResult(const OptznResult &R) const {
979 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
980 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
981 }));
982 }
983
984 void resetPhiOptznState() {
985 Paths.clear();
986 VisitedPhis.clear();
987 }
988
989public:
990 ClobberWalker(const MemorySSA &MSSA, AliasAnalysis &AA, DominatorTree &DT,
991 WalkerCache &WC)
992 : MSSA(MSSA), AA(AA), DT(DT), WC(WC), UseCache(true) {}
993
994 void reset() { WalkTargetCache.clear(); }
995
996 /// Finds the nearest clobber for the given query, optimizing phis if
997 /// possible.
998 MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q,
999 bool UseWalkerCache = true) {
1000 setUseCache(UseWalkerCache);
1001 Query = &Q;
1002
1003 MemoryAccess *Current = Start;
1004 // This walker pretends uses don't exist. If we're handed one, silently grab
1005 // its def. (This has the nice side-effect of ensuring we never cache uses)
1006 if (auto *MU = dyn_cast<MemoryUse>(Start))
1007 Current = MU->getDefiningAccess();
1008
1009 DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
1010 // Fast path for the overly-common case (no crazy phi optimization
1011 // necessary)
1012 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
George Burgess IV93ea19b2016-07-24 07:03:49 +00001013 MemoryAccess *Result;
George Burgess IV5f308972016-07-19 01:29:15 +00001014 if (WalkResult.IsKnownClobber) {
1015 cacheDefPath(FirstDesc, WalkResult.Result);
George Burgess IV93ea19b2016-07-24 07:03:49 +00001016 Result = WalkResult.Result;
1017 } else {
1018 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
1019 Current, Q.StartingLoc);
1020 verifyOptResult(OptRes);
1021 cacheOptResult(OptRes);
1022 resetPhiOptznState();
1023 Result = OptRes.PrimaryClobber.Clobber;
George Burgess IV5f308972016-07-19 01:29:15 +00001024 }
1025
George Burgess IV5f308972016-07-19 01:29:15 +00001026#ifdef EXPENSIVE_CHECKS
George Burgess IV93ea19b2016-07-24 07:03:49 +00001027 checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
George Burgess IV5f308972016-07-19 01:29:15 +00001028#endif
George Burgess IV93ea19b2016-07-24 07:03:49 +00001029 return Result;
George Burgess IV5f308972016-07-19 01:29:15 +00001030 }
Geoff Berrycdf53332016-08-08 17:52:01 +00001031
1032 void verify(const MemorySSA *MSSA) { assert(MSSA == &this->MSSA); }
George Burgess IV5f308972016-07-19 01:29:15 +00001033};
1034
1035struct RenamePassData {
1036 DomTreeNode *DTN;
1037 DomTreeNode::const_iterator ChildIt;
1038 MemoryAccess *IncomingVal;
1039
1040 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
1041 MemoryAccess *M)
1042 : DTN(D), ChildIt(It), IncomingVal(M) {}
1043 void swap(RenamePassData &RHS) {
1044 std::swap(DTN, RHS.DTN);
1045 std::swap(ChildIt, RHS.ChildIt);
1046 std::swap(IncomingVal, RHS.IncomingVal);
1047 }
1048};
1049} // anonymous namespace
1050
1051namespace llvm {
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001052/// \brief A MemorySSAWalker that does AA walks and caching of lookups to
1053/// disambiguate accesses.
1054///
1055/// FIXME: The current implementation of this can take quadratic space in rare
1056/// cases. This can be fixed, but it is something to note until it is fixed.
1057///
1058/// In order to trigger this behavior, you need to store to N distinct locations
1059/// (that AA can prove don't alias), perform M stores to other memory
1060/// locations that AA can prove don't alias any of the initial N locations, and
1061/// then load from all of the N locations. In this case, we insert M cache
1062/// entries for each of the N loads.
1063///
1064/// For example:
1065/// define i32 @foo() {
1066/// %a = alloca i32, align 4
1067/// %b = alloca i32, align 4
1068/// store i32 0, i32* %a, align 4
1069/// store i32 0, i32* %b, align 4
1070///
1071/// ; Insert M stores to other memory that doesn't alias %a or %b here
1072///
1073/// %c = load i32, i32* %a, align 4 ; Caches M entries in
1074/// ; CachedUpwardsClobberingAccess for the
1075/// ; MemoryLocation %a
1076/// %d = load i32, i32* %b, align 4 ; Caches M entries in
1077/// ; CachedUpwardsClobberingAccess for the
1078/// ; MemoryLocation %b
1079///
1080/// ; For completeness' sake, loading %a or %b again would not cache *another*
1081/// ; M entries.
1082/// %r = add i32 %c, %d
1083/// ret i32 %r
1084/// }
1085class MemorySSA::CachingWalker final : public MemorySSAWalker {
George Burgess IV5f308972016-07-19 01:29:15 +00001086 WalkerCache Cache;
1087 ClobberWalker Walker;
1088 bool AutoResetWalker;
1089
1090 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, UpwardsMemoryQuery &);
1091 void verifyRemoved(MemoryAccess *);
1092
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001093public:
1094 CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *);
1095 ~CachingWalker() override;
1096
George Burgess IV400ae402016-07-20 19:51:34 +00001097 using MemorySSAWalker::getClobberingMemoryAccess;
1098 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override;
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001099 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
1100 MemoryLocation &) override;
1101 void invalidateInfo(MemoryAccess *) override;
1102
George Burgess IV5f308972016-07-19 01:29:15 +00001103 /// Whether we call resetClobberWalker() after each time we *actually* walk to
1104 /// answer a clobber query.
1105 void setAutoResetWalker(bool AutoReset) { AutoResetWalker = AutoReset; }
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001106
George Burgess IV5f308972016-07-19 01:29:15 +00001107 /// Drop the walker's persistent data structures. At the moment, this means
1108 /// "drop the walker's cache of BasicBlocks ->
1109 /// earliest-MemoryAccess-we-can-optimize-to". This is necessary if we're
1110 /// going to have DT updates, if we remove MemoryAccesses, etc.
1111 void resetClobberWalker() { Walker.reset(); }
Geoff Berrycdf53332016-08-08 17:52:01 +00001112
1113 void verify(const MemorySSA *MSSA) override {
1114 MemorySSAWalker::verify(MSSA);
1115 Walker.verify(MSSA);
1116 }
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001117};
George Burgess IVe1100f52016-02-02 22:46:49 +00001118
George Burgess IVe1100f52016-02-02 22:46:49 +00001119/// \brief Rename a single basic block into MemorySSA form.
1120/// Uses the standard SSA renaming algorithm.
1121/// \returns The new incoming value.
1122MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB,
1123 MemoryAccess *IncomingVal) {
1124 auto It = PerBlockAccesses.find(BB);
1125 // Skip most processing if the list is empty.
1126 if (It != PerBlockAccesses.end()) {
Daniel Berlinada263d2016-06-20 20:21:33 +00001127 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001128 for (MemoryAccess &L : *Accesses) {
Daniel Berlin868381b2016-08-22 19:14:16 +00001129 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) {
1130 if (MUD->getDefiningAccess() == nullptr)
1131 MUD->setDefiningAccess(IncomingVal);
1132 if (isa<MemoryDef>(&L))
1133 IncomingVal = &L;
1134 } else {
George Burgess IVe1100f52016-02-02 22:46:49 +00001135 IncomingVal = &L;
George Burgess IVe1100f52016-02-02 22:46:49 +00001136 }
1137 }
1138 }
1139
1140 // Pass through values to our successors
1141 for (const BasicBlock *S : successors(BB)) {
1142 auto It = PerBlockAccesses.find(S);
1143 // Rename the phi nodes in our successor block
1144 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1145 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +00001146 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001147 auto *Phi = cast<MemoryPhi>(&Accesses->front());
George Burgess IVe1100f52016-02-02 22:46:49 +00001148 Phi->addIncoming(IncomingVal, BB);
1149 }
1150
1151 return IncomingVal;
1152}
1153
1154/// \brief This is the standard SSA renaming algorithm.
1155///
1156/// We walk the dominator tree in preorder, renaming accesses, and then filling
1157/// in phi nodes in our successors.
1158void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
1159 SmallPtrSet<BasicBlock *, 16> &Visited) {
1160 SmallVector<RenamePassData, 32> WorkStack;
1161 IncomingVal = renameBlock(Root->getBlock(), IncomingVal);
1162 WorkStack.push_back({Root, Root->begin(), IncomingVal});
1163 Visited.insert(Root->getBlock());
1164
1165 while (!WorkStack.empty()) {
1166 DomTreeNode *Node = WorkStack.back().DTN;
1167 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
1168 IncomingVal = WorkStack.back().IncomingVal;
1169
1170 if (ChildIt == Node->end()) {
1171 WorkStack.pop_back();
1172 } else {
1173 DomTreeNode *Child = *ChildIt;
1174 ++WorkStack.back().ChildIt;
1175 BasicBlock *BB = Child->getBlock();
1176 Visited.insert(BB);
1177 IncomingVal = renameBlock(BB, IncomingVal);
1178 WorkStack.push_back({Child, Child->begin(), IncomingVal});
1179 }
1180 }
1181}
1182
1183/// \brief Compute dominator levels, used by the phi insertion algorithm above.
1184void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) {
1185 for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode());
1186 DFI != DFE; ++DFI)
1187 DomLevels[*DFI] = DFI.getPathLength() - 1;
1188}
1189
George Burgess IVa362b092016-07-06 00:28:43 +00001190/// \brief This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +00001191/// unreachable blocks, and marking all other unreachable MemoryAccess's as
1192/// being uses of the live on entry definition.
1193void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
1194 assert(!DT->isReachableFromEntry(BB) &&
1195 "Reachable block found while handling unreachable blocks");
1196
Daniel Berlinfc7e6512016-07-06 05:32:05 +00001197 // Make sure phi nodes in our reachable successors end up with a
1198 // LiveOnEntryDef for our incoming edge, even though our block is forward
1199 // unreachable. We could just disconnect these blocks from the CFG fully,
1200 // but we do not right now.
1201 for (const BasicBlock *S : successors(BB)) {
1202 if (!DT->isReachableFromEntry(S))
1203 continue;
1204 auto It = PerBlockAccesses.find(S);
1205 // Rename the phi nodes in our successor block
1206 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1207 continue;
1208 AccessList *Accesses = It->second.get();
1209 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1210 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1211 }
1212
George Burgess IVe1100f52016-02-02 22:46:49 +00001213 auto It = PerBlockAccesses.find(BB);
1214 if (It == PerBlockAccesses.end())
1215 return;
1216
1217 auto &Accesses = It->second;
1218 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1219 auto Next = std::next(AI);
1220 // If we have a phi, just remove it. We are going to replace all
1221 // users with live on entry.
1222 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1223 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1224 else
1225 Accesses->erase(AI);
1226 AI = Next;
1227 }
1228}
1229
Geoff Berryb96d3b22016-06-01 21:30:40 +00001230MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
1231 : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
1232 NextID(0) {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001233 buildMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001234}
1235
George Burgess IVe1100f52016-02-02 22:46:49 +00001236MemorySSA::~MemorySSA() {
1237 // Drop all our references
1238 for (const auto &Pair : PerBlockAccesses)
1239 for (MemoryAccess &MA : *Pair.second)
1240 MA.dropAllReferences();
1241}
1242
Daniel Berlin14300262016-06-21 18:39:20 +00001243MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001244 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1245
1246 if (Res.second)
Daniel Berlinada263d2016-06-20 20:21:33 +00001247 Res.first->second = make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001248 return Res.first->second.get();
1249}
1250
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001251/// This class is a batch walker of all MemoryUse's in the program, and points
1252/// their defining access at the thing that actually clobbers them. Because it
1253/// is a batch walker that touches everything, it does not operate like the
1254/// other walkers. This walker is basically performing a top-down SSA renaming
1255/// pass, where the version stack is used as the cache. This enables it to be
1256/// significantly more time and memory efficient than using the regular walker,
1257/// which is walking bottom-up.
1258class MemorySSA::OptimizeUses {
1259public:
1260 OptimizeUses(MemorySSA *MSSA, MemorySSAWalker *Walker, AliasAnalysis *AA,
1261 DominatorTree *DT)
1262 : MSSA(MSSA), Walker(Walker), AA(AA), DT(DT) {
1263 Walker = MSSA->getWalker();
1264 }
1265
1266 void optimizeUses();
1267
1268private:
1269 /// This represents where a given memorylocation is in the stack.
1270 struct MemlocStackInfo {
1271 // This essentially is keeping track of versions of the stack. Whenever
1272 // the stack changes due to pushes or pops, these versions increase.
1273 unsigned long StackEpoch;
1274 unsigned long PopEpoch;
1275 // This is the lower bound of places on the stack to check. It is equal to
1276 // the place the last stack walk ended.
1277 // Note: Correctness depends on this being initialized to 0, which densemap
1278 // does
1279 unsigned long LowerBound;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001280 const BasicBlock *LowerBoundBlock;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001281 // This is where the last walk for this memory location ended.
1282 unsigned long LastKill;
1283 bool LastKillValid;
1284 };
1285 void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1286 SmallVectorImpl<MemoryAccess *> &,
1287 DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
1288 MemorySSA *MSSA;
1289 MemorySSAWalker *Walker;
1290 AliasAnalysis *AA;
1291 DominatorTree *DT;
1292};
1293
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001294/// Optimize the uses in a given block This is basically the SSA renaming
1295/// algorithm, with one caveat: We are able to use a single stack for all
1296/// MemoryUses. This is because the set of *possible* reaching MemoryDefs is
1297/// the same for every MemoryUse. The *actual* clobbering MemoryDef is just
1298/// going to be some position in that stack of possible ones.
1299///
1300/// We track the stack positions that each MemoryLocation needs
1301/// to check, and last ended at. This is because we only want to check the
1302/// things that changed since last time. The same MemoryLocation should
1303/// get clobbered by the same store (getModRefInfo does not use invariantness or
1304/// things like this, and if they start, we can modify MemoryLocOrCall to
1305/// include relevant data)
1306void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1307 const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1308 SmallVectorImpl<MemoryAccess *> &VersionStack,
1309 DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
1310
1311 /// If no accesses, nothing to do.
1312 MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
1313 if (Accesses == nullptr)
1314 return;
1315
1316 // Pop everything that doesn't dominate the current block off the stack,
1317 // increment the PopEpoch to account for this.
1318 while (!VersionStack.empty()) {
1319 BasicBlock *BackBlock = VersionStack.back()->getBlock();
1320 if (DT->dominates(BackBlock, BB))
1321 break;
1322 while (VersionStack.back()->getBlock() == BackBlock)
1323 VersionStack.pop_back();
1324 ++PopEpoch;
1325 }
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001326 for (MemoryAccess &MA : *Accesses) {
1327 auto *MU = dyn_cast<MemoryUse>(&MA);
1328 if (!MU) {
1329 VersionStack.push_back(&MA);
1330 ++StackEpoch;
1331 continue;
1332 }
1333
George Burgess IV024f3d22016-08-03 19:57:02 +00001334 if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
1335 MU->setDefiningAccess(MSSA->getLiveOnEntryDef());
1336 continue;
1337 }
1338
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001339 MemoryLocOrCall UseMLOC(MU);
1340 auto &LocInfo = LocStackInfo[UseMLOC];
Daniel Berlin26fcea92016-08-02 20:02:21 +00001341 // If the pop epoch changed, it means we've removed stuff from top of
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001342 // stack due to changing blocks. We may have to reset the lower bound or
1343 // last kill info.
1344 if (LocInfo.PopEpoch != PopEpoch) {
1345 LocInfo.PopEpoch = PopEpoch;
1346 LocInfo.StackEpoch = StackEpoch;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001347 // If the lower bound was in something that no longer dominates us, we
1348 // have to reset it.
1349 // We can't simply track stack size, because the stack may have had
1350 // pushes/pops in the meantime.
1351 // XXX: This is non-optimal, but only is slower cases with heavily
1352 // branching dominator trees. To get the optimal number of queries would
1353 // be to make lowerbound and lastkill a per-loc stack, and pop it until
1354 // the top of that stack dominates us. This does not seem worth it ATM.
1355 // A much cheaper optimization would be to always explore the deepest
1356 // branch of the dominator tree first. This will guarantee this resets on
1357 // the smallest set of blocks.
1358 if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
Daniel Berlin1e98c042016-09-26 17:22:54 +00001359 !DT->dominates(LocInfo.LowerBoundBlock, BB)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001360 // Reset the lower bound of things to check.
1361 // TODO: Some day we should be able to reset to last kill, rather than
1362 // 0.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001363 LocInfo.LowerBound = 0;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001364 LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001365 LocInfo.LastKillValid = false;
1366 }
1367 } else if (LocInfo.StackEpoch != StackEpoch) {
1368 // If all that has changed is the StackEpoch, we only have to check the
1369 // new things on the stack, because we've checked everything before. In
1370 // this case, the lower bound of things to check remains the same.
1371 LocInfo.PopEpoch = PopEpoch;
1372 LocInfo.StackEpoch = StackEpoch;
1373 }
1374 if (!LocInfo.LastKillValid) {
1375 LocInfo.LastKill = VersionStack.size() - 1;
1376 LocInfo.LastKillValid = true;
1377 }
1378
1379 // At this point, we should have corrected last kill and LowerBound to be
1380 // in bounds.
1381 assert(LocInfo.LowerBound < VersionStack.size() &&
1382 "Lower bound out of range");
1383 assert(LocInfo.LastKill < VersionStack.size() &&
1384 "Last kill info out of range");
1385 // In any case, the new upper bound is the top of the stack.
1386 unsigned long UpperBound = VersionStack.size() - 1;
1387
1388 if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
Daniel Berlin26fcea92016-08-02 20:02:21 +00001389 DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
1390 << *(MU->getMemoryInst()) << ")"
1391 << " because there are " << UpperBound - LocInfo.LowerBound
1392 << " stores to disambiguate\n");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001393 // Because we did not walk, LastKill is no longer valid, as this may
1394 // have been a kill.
1395 LocInfo.LastKillValid = false;
1396 continue;
1397 }
1398 bool FoundClobberResult = false;
1399 while (UpperBound > LocInfo.LowerBound) {
1400 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1401 // For phis, use the walker, see where we ended up, go there
1402 Instruction *UseInst = MU->getMemoryInst();
1403 MemoryAccess *Result = Walker->getClobberingMemoryAccess(UseInst);
1404 // We are guaranteed to find it or something is wrong
1405 while (VersionStack[UpperBound] != Result) {
1406 assert(UpperBound != 0);
1407 --UpperBound;
1408 }
1409 FoundClobberResult = true;
1410 break;
1411 }
1412
1413 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
Daniel Berlindf101192016-08-03 00:01:46 +00001414 // If the lifetime of the pointer ends at this instruction, it's live on
1415 // entry.
1416 if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1417 // Reset UpperBound to liveOnEntryDef's place in the stack
1418 UpperBound = 0;
1419 FoundClobberResult = true;
1420 break;
1421 }
Daniel Berlindff31de2016-08-02 21:57:52 +00001422 if (instructionClobbersQuery(MD, MU, UseMLOC, *AA)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001423 FoundClobberResult = true;
1424 break;
1425 }
1426 --UpperBound;
1427 }
1428 // At the end of this loop, UpperBound is either a clobber, or lower bound
1429 // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1430 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
1431 MU->setDefiningAccess(VersionStack[UpperBound]);
1432 // We were last killed now by where we got to
1433 LocInfo.LastKill = UpperBound;
1434 } else {
1435 // Otherwise, we checked all the new ones, and now we know we can get to
1436 // LastKill.
1437 MU->setDefiningAccess(VersionStack[LocInfo.LastKill]);
1438 }
1439 LocInfo.LowerBound = VersionStack.size() - 1;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001440 LocInfo.LowerBoundBlock = BB;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001441 }
1442}
1443
1444/// Optimize uses to point to their actual clobbering definitions.
1445void MemorySSA::OptimizeUses::optimizeUses() {
1446
1447 // We perform a non-recursive top-down dominator tree walk
1448 struct StackInfo {
1449 const DomTreeNode *Node;
1450 DomTreeNode::const_iterator Iter;
1451 };
1452
1453 SmallVector<MemoryAccess *, 16> VersionStack;
1454 SmallVector<StackInfo, 16> DomTreeWorklist;
1455 DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001456 VersionStack.push_back(MSSA->getLiveOnEntryDef());
1457
1458 unsigned long StackEpoch = 1;
1459 unsigned long PopEpoch = 1;
Daniel Berlin7ac3d742016-08-05 22:09:14 +00001460 for (const auto *DomNode : depth_first(DT->getRootNode()))
1461 optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1462 LocStackInfo);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001463}
1464
Daniel Berlin3d512a22016-08-22 19:14:30 +00001465void MemorySSA::placePHINodes(
Daniel Berlin1e98c042016-09-26 17:22:54 +00001466 const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks) {
Daniel Berlin3d512a22016-08-22 19:14:30 +00001467 // Determine where our MemoryPhi's should go
1468 ForwardIDFCalculator IDFs(*DT);
1469 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001470 SmallVector<BasicBlock *, 32> IDFBlocks;
1471 IDFs.calculate(IDFBlocks);
1472
1473 // Now place MemoryPhi nodes.
1474 for (auto &BB : IDFBlocks) {
1475 // Insert phi node
1476 AccessList *Accesses = getOrCreateAccessList(BB);
1477 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
1478 ValueToMemoryAccess[BB] = Phi;
1479 // Phi's always are placed at the front of the block.
1480 Accesses->push_front(Phi);
1481 }
1482}
1483
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001484void MemorySSA::buildMemorySSA() {
George Burgess IVe1100f52016-02-02 22:46:49 +00001485 // We create an access to represent "live on entry", for things like
1486 // arguments or users of globals, where the memory they use is defined before
1487 // the beginning of the function. We do not actually insert it into the IR.
1488 // We do not define a live on exit for the immediate uses, and thus our
1489 // semantics do *not* imply that something with no immediate uses can simply
1490 // be removed.
1491 BasicBlock &StartingPoint = F.getEntryBlock();
1492 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
1493 &StartingPoint, NextID++);
1494
1495 // We maintain lists of memory accesses per-block, trading memory for time. We
1496 // could just look up the memory access for every possible instruction in the
1497 // stream.
1498 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001499 SmallPtrSet<BasicBlock *, 32> DefUseBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001500 // Go through each block, figure out where defs occur, and chain together all
1501 // the accesses.
1502 for (BasicBlock &B : F) {
Daniel Berlin7898ca62016-02-07 01:52:15 +00001503 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001504 AccessList *Accesses = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001505 for (Instruction &I : B) {
Peter Collingbourneffecb142016-05-26 01:19:17 +00001506 MemoryUseOrDef *MUD = createNewAccess(&I);
George Burgess IVb42b7622016-03-11 19:34:03 +00001507 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001508 continue;
George Burgess IV3887a412016-03-21 21:25:39 +00001509 InsertIntoDef |= isa<MemoryDef>(MUD);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001510
George Burgess IVe1100f52016-02-02 22:46:49 +00001511 if (!Accesses)
1512 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001513 Accesses->push_back(MUD);
George Burgess IVe1100f52016-02-02 22:46:49 +00001514 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001515 if (InsertIntoDef)
1516 DefiningBlocks.insert(&B);
George Burgess IV3887a412016-03-21 21:25:39 +00001517 if (Accesses)
Daniel Berlin1b51a292016-02-07 01:52:19 +00001518 DefUseBlocks.insert(&B);
1519 }
Daniel Berlin1e98c042016-09-26 17:22:54 +00001520 placePHINodes(DefiningBlocks);
George Burgess IVe1100f52016-02-02 22:46:49 +00001521
1522 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1523 // filled in with all blocks.
1524 SmallPtrSet<BasicBlock *, 16> Visited;
1525 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1526
George Burgess IV5f308972016-07-19 01:29:15 +00001527 CachingWalker *Walker = getWalkerImpl();
1528
1529 // We're doing a batch of updates; don't drop useful caches between them.
1530 Walker->setAutoResetWalker(false);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001531 OptimizeUses(this, Walker, AA, DT).optimizeUses();
George Burgess IV5f308972016-07-19 01:29:15 +00001532 Walker->setAutoResetWalker(true);
1533 Walker->resetClobberWalker();
1534
George Burgess IVe1100f52016-02-02 22:46:49 +00001535 // Mark the uses in unreachable blocks as live on entry, so that they go
1536 // somewhere.
1537 for (auto &BB : F)
1538 if (!Visited.count(&BB))
1539 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001540}
George Burgess IVe1100f52016-02-02 22:46:49 +00001541
George Burgess IV5f308972016-07-19 01:29:15 +00001542MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1543
1544MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001545 if (Walker)
1546 return Walker.get();
1547
1548 Walker = make_unique<CachingWalker>(this, AA, DT);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001549 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001550}
1551
Daniel Berlin14300262016-06-21 18:39:20 +00001552MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1553 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
1554 AccessList *Accesses = getOrCreateAccessList(BB);
1555 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001556 ValueToMemoryAccess[BB] = Phi;
Daniel Berlin14300262016-06-21 18:39:20 +00001557 // Phi's always are placed at the front of the block.
1558 Accesses->push_front(Phi);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001559 BlockNumberingValid.erase(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001560 return Phi;
1561}
1562
1563MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
1564 MemoryAccess *Definition) {
1565 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1566 MemoryUseOrDef *NewAccess = createNewAccess(I);
1567 assert(
1568 NewAccess != nullptr &&
1569 "Tried to create a memory access for a non-memory touching instruction");
1570 NewAccess->setDefiningAccess(Definition);
1571 return NewAccess;
1572}
1573
1574MemoryAccess *MemorySSA::createMemoryAccessInBB(Instruction *I,
1575 MemoryAccess *Definition,
1576 const BasicBlock *BB,
1577 InsertionPlace Point) {
1578 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1579 auto *Accesses = getOrCreateAccessList(BB);
1580 if (Point == Beginning) {
1581 // It goes after any phi nodes
David Majnemer42531262016-08-12 03:55:06 +00001582 auto AI = find_if(
1583 *Accesses, [](const MemoryAccess &MA) { return !isa<MemoryPhi>(MA); });
Daniel Berlin14300262016-06-21 18:39:20 +00001584
1585 Accesses->insert(AI, NewAccess);
1586 } else {
1587 Accesses->push_back(NewAccess);
1588 }
Daniel Berlin5c46b942016-07-19 22:49:43 +00001589 BlockNumberingValid.erase(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001590 return NewAccess;
1591}
1592MemoryAccess *MemorySSA::createMemoryAccessBefore(Instruction *I,
1593 MemoryAccess *Definition,
1594 MemoryAccess *InsertPt) {
1595 assert(I->getParent() == InsertPt->getBlock() &&
1596 "New and old access must be in the same block");
1597 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1598 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
1599 Accesses->insert(AccessList::iterator(InsertPt), NewAccess);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001600 BlockNumberingValid.erase(InsertPt->getBlock());
Daniel Berlin14300262016-06-21 18:39:20 +00001601 return NewAccess;
1602}
1603
1604MemoryAccess *MemorySSA::createMemoryAccessAfter(Instruction *I,
1605 MemoryAccess *Definition,
1606 MemoryAccess *InsertPt) {
1607 assert(I->getParent() == InsertPt->getBlock() &&
1608 "New and old access must be in the same block");
1609 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1610 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
1611 Accesses->insertAfter(AccessList::iterator(InsertPt), NewAccess);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001612 BlockNumberingValid.erase(InsertPt->getBlock());
Daniel Berlin14300262016-06-21 18:39:20 +00001613 return NewAccess;
1614}
1615
George Burgess IVe1100f52016-02-02 22:46:49 +00001616/// \brief Helper function to create new memory accesses
Peter Collingbourneffecb142016-05-26 01:19:17 +00001617MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001618 // The assume intrinsic has a control dependency which we model by claiming
1619 // that it writes arbitrarily. Ignore that fake memory dependency here.
1620 // FIXME: Replace this special casing with a more accurate modelling of
1621 // assume's control dependency.
1622 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1623 if (II->getIntrinsicID() == Intrinsic::assume)
1624 return nullptr;
1625
George Burgess IVe1100f52016-02-02 22:46:49 +00001626 // Find out what affect this instruction has on memory.
1627 ModRefInfo ModRef = AA->getModRefInfo(I);
1628 bool Def = bool(ModRef & MRI_Mod);
1629 bool Use = bool(ModRef & MRI_Ref);
1630
1631 // It's possible for an instruction to not modify memory at all. During
1632 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +00001633 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +00001634 return nullptr;
1635
1636 assert((Def || Use) &&
1637 "Trying to create a memory access with a non-memory instruction");
1638
George Burgess IVb42b7622016-03-11 19:34:03 +00001639 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001640 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +00001641 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +00001642 else
George Burgess IVb42b7622016-03-11 19:34:03 +00001643 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
Daniel Berlin5130cc82016-07-31 21:08:20 +00001644 ValueToMemoryAccess[I] = MUD;
George Burgess IVb42b7622016-03-11 19:34:03 +00001645 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001646}
1647
1648MemoryAccess *MemorySSA::findDominatingDef(BasicBlock *UseBlock,
1649 enum InsertionPlace Where) {
1650 // Handle the initial case
1651 if (Where == Beginning)
1652 // The only thing that could define us at the beginning is a phi node
1653 if (MemoryPhi *Phi = getMemoryAccess(UseBlock))
1654 return Phi;
1655
1656 DomTreeNode *CurrNode = DT->getNode(UseBlock);
1657 // Need to be defined by our dominator
1658 if (Where == Beginning)
1659 CurrNode = CurrNode->getIDom();
1660 Where = End;
1661 while (CurrNode) {
1662 auto It = PerBlockAccesses.find(CurrNode->getBlock());
1663 if (It != PerBlockAccesses.end()) {
1664 auto &Accesses = It->second;
David Majnemerd7708772016-06-24 04:05:21 +00001665 for (MemoryAccess &RA : reverse(*Accesses)) {
1666 if (isa<MemoryDef>(RA) || isa<MemoryPhi>(RA))
1667 return &RA;
George Burgess IVe1100f52016-02-02 22:46:49 +00001668 }
1669 }
1670 CurrNode = CurrNode->getIDom();
1671 }
1672 return LiveOnEntryDef.get();
1673}
1674
1675/// \brief Returns true if \p Replacer dominates \p Replacee .
1676bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1677 const MemoryAccess *Replacee) const {
1678 if (isa<MemoryUseOrDef>(Replacee))
1679 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1680 const auto *MP = cast<MemoryPhi>(Replacee);
1681 // For a phi node, the use occurs in the predecessor block of the phi node.
1682 // Since we may occur multiple times in the phi node, we have to check each
1683 // operand to ensure Replacer dominates each operand where Replacee occurs.
1684 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +00001685 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +00001686 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1687 return false;
1688 }
1689 return true;
1690}
1691
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001692/// \brief If all arguments of a MemoryPHI are defined by the same incoming
1693/// argument, return that argument.
1694static MemoryAccess *onlySingleValue(MemoryPhi *MP) {
1695 MemoryAccess *MA = nullptr;
1696
1697 for (auto &Arg : MP->operands()) {
1698 if (!MA)
1699 MA = cast<MemoryAccess>(Arg);
1700 else if (MA != Arg)
1701 return nullptr;
1702 }
1703 return MA;
1704}
1705
1706/// \brief Properly remove \p MA from all of MemorySSA's lookup tables.
1707///
1708/// Because of the way the intrusive list and use lists work, it is important to
1709/// do removal in the right order.
1710void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1711 assert(MA->use_empty() &&
1712 "Trying to remove memory access that still has uses");
Daniel Berlin5c46b942016-07-19 22:49:43 +00001713 BlockNumbering.erase(MA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001714 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
1715 MUD->setDefiningAccess(nullptr);
1716 // Invalidate our walker's cache if necessary
1717 if (!isa<MemoryUse>(MA))
1718 Walker->invalidateInfo(MA);
1719 // The call below to erase will destroy MA, so we can't change the order we
1720 // are doing things here
1721 Value *MemoryInst;
1722 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1723 MemoryInst = MUD->getMemoryInst();
1724 } else {
1725 MemoryInst = MA->getBlock();
1726 }
Daniel Berlin5130cc82016-07-31 21:08:20 +00001727 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1728 if (VMA->second == MA)
1729 ValueToMemoryAccess.erase(VMA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001730
George Burgess IVe0e6e482016-03-02 02:35:04 +00001731 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
Daniel Berlinada263d2016-06-20 20:21:33 +00001732 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001733 Accesses->erase(MA);
George Burgess IVe0e6e482016-03-02 02:35:04 +00001734 if (Accesses->empty())
1735 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001736}
1737
1738void MemorySSA::removeMemoryAccess(MemoryAccess *MA) {
1739 assert(!isLiveOnEntryDef(MA) && "Trying to remove the live on entry def");
1740 // We can only delete phi nodes if they have no uses, or we can replace all
1741 // uses with a single definition.
1742 MemoryAccess *NewDefTarget = nullptr;
1743 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) {
1744 // Note that it is sufficient to know that all edges of the phi node have
1745 // the same argument. If they do, by the definition of dominance frontiers
1746 // (which we used to place this phi), that argument must dominate this phi,
1747 // and thus, must dominate the phi's uses, and so we will not hit the assert
1748 // below.
1749 NewDefTarget = onlySingleValue(MP);
1750 assert((NewDefTarget || MP->use_empty()) &&
1751 "We can't delete this memory phi");
1752 } else {
1753 NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
1754 }
1755
1756 // Re-point the uses at our defining access
1757 if (!MA->use_empty())
1758 MA->replaceAllUsesWith(NewDefTarget);
1759
1760 // The call below to erase will destroy MA, so we can't change the order we
1761 // are doing things here
1762 removeFromLookups(MA);
1763}
1764
George Burgess IVe1100f52016-02-02 22:46:49 +00001765void MemorySSA::print(raw_ostream &OS) const {
1766 MemorySSAAnnotatedWriter Writer(this);
1767 F.print(OS, &Writer);
1768}
1769
1770void MemorySSA::dump() const {
1771 MemorySSAAnnotatedWriter Writer(this);
1772 F.print(dbgs(), &Writer);
1773}
1774
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001775void MemorySSA::verifyMemorySSA() const {
1776 verifyDefUses(F);
1777 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001778 verifyOrdering(F);
Geoff Berrycdf53332016-08-08 17:52:01 +00001779 Walker->verify(this);
Daniel Berlin14300262016-06-21 18:39:20 +00001780}
1781
1782/// \brief Verify that the order and existence of MemoryAccesses matches the
1783/// order and existence of memory affecting instructions.
1784void MemorySSA::verifyOrdering(Function &F) const {
1785 // Walk all the blocks, comparing what the lookups think and what the access
1786 // lists think, as well as the order in the blocks vs the order in the access
1787 // lists.
1788 SmallVector<MemoryAccess *, 32> ActualAccesses;
1789 for (BasicBlock &B : F) {
1790 const AccessList *AL = getBlockAccesses(&B);
1791 MemoryAccess *Phi = getMemoryAccess(&B);
1792 if (Phi)
1793 ActualAccesses.push_back(Phi);
1794 for (Instruction &I : B) {
1795 MemoryAccess *MA = getMemoryAccess(&I);
1796 assert((!MA || AL) && "We have memory affecting instructions "
1797 "in this block but they are not in the "
1798 "access list");
1799 if (MA)
1800 ActualAccesses.push_back(MA);
1801 }
1802 // Either we hit the assert, really have no accesses, or we have both
1803 // accesses and an access list
1804 if (!AL)
1805 continue;
1806 assert(AL->size() == ActualAccesses.size() &&
1807 "We don't have the same number of accesses in the block as on the "
1808 "access list");
1809 auto ALI = AL->begin();
1810 auto AAI = ActualAccesses.begin();
1811 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1812 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1813 ++ALI;
1814 ++AAI;
1815 }
1816 ActualAccesses.clear();
1817 }
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001818}
1819
George Burgess IVe1100f52016-02-02 22:46:49 +00001820/// \brief Verify the domination properties of MemorySSA by checking that each
1821/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001822void MemorySSA::verifyDomination(Function &F) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001823#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001824 for (BasicBlock &B : F) {
1825 // Phi nodes are attached to basic blocks
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001826 if (MemoryPhi *MP = getMemoryAccess(&B))
1827 for (const Use &U : MP->uses())
1828 assert(dominates(MP, U) && "Memory PHI does not dominate it's uses");
Daniel Berlin7af95872016-08-05 21:47:20 +00001829
George Burgess IVe1100f52016-02-02 22:46:49 +00001830 for (Instruction &I : B) {
1831 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
1832 if (!MD)
1833 continue;
1834
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001835 for (const Use &U : MD->uses())
1836 assert(dominates(MD, U) && "Memory Def does not dominate it's uses");
George Burgess IVe1100f52016-02-02 22:46:49 +00001837 }
1838 }
Daniel Berlin7af95872016-08-05 21:47:20 +00001839#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001840}
1841
1842/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
1843/// appears in the use list of \p Def.
Daniel Berlin7af95872016-08-05 21:47:20 +00001844
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001845void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001846#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001847 // The live on entry use may cause us to get a NULL def here
Daniel Berlin7af95872016-08-05 21:47:20 +00001848 if (!Def)
1849 assert(isLiveOnEntryDef(Use) &&
1850 "Null def but use not point to live on entry def");
1851 else
Daniel Berlinda2f38e2016-08-11 21:26:50 +00001852 assert(is_contained(Def->users(), Use) &&
Daniel Berlin7af95872016-08-05 21:47:20 +00001853 "Did not find use in def's use list");
1854#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001855}
1856
1857/// \brief Verify the immediate use information, by walking all the memory
1858/// accesses and verifying that, for each use, it appears in the
1859/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001860void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001861 for (BasicBlock &B : F) {
1862 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00001863 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00001864 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
1865 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00001866 "Incomplete MemoryPhi Node");
George Burgess IVe1100f52016-02-02 22:46:49 +00001867 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1868 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Daniel Berlin14300262016-06-21 18:39:20 +00001869 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001870
1871 for (Instruction &I : B) {
1872 if (MemoryAccess *MA = getMemoryAccess(&I)) {
1873 assert(isa<MemoryUseOrDef>(MA) &&
1874 "Found a phi node not attached to a bb");
1875 verifyUseInDefs(cast<MemoryUseOrDef>(MA)->getDefiningAccess(), MA);
1876 }
1877 }
1878 }
1879}
1880
1881MemoryAccess *MemorySSA::getMemoryAccess(const Value *I) const {
Daniel Berlinf6c9ae92016-02-10 17:41:25 +00001882 return ValueToMemoryAccess.lookup(I);
George Burgess IVe1100f52016-02-02 22:46:49 +00001883}
1884
1885MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
1886 return cast_or_null<MemoryPhi>(getMemoryAccess((const Value *)BB));
1887}
1888
Daniel Berlin5c46b942016-07-19 22:49:43 +00001889/// Perform a local numbering on blocks so that instruction ordering can be
1890/// determined in constant time.
1891/// TODO: We currently just number in order. If we numbered by N, we could
1892/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
1893/// log2(N) sequences of mixed before and after) without needing to invalidate
1894/// the numbering.
1895void MemorySSA::renumberBlock(const BasicBlock *B) const {
1896 // The pre-increment ensures the numbers really start at 1.
1897 unsigned long CurrentNumber = 0;
1898 const AccessList *AL = getBlockAccesses(B);
1899 assert(AL != nullptr && "Asking to renumber an empty block");
1900 for (const auto &I : *AL)
1901 BlockNumbering[&I] = ++CurrentNumber;
1902 BlockNumberingValid.insert(B);
1903}
1904
George Burgess IVe1100f52016-02-02 22:46:49 +00001905/// \brief Determine, for two memory accesses in the same block,
1906/// whether \p Dominator dominates \p Dominatee.
1907/// \returns True if \p Dominator dominates \p Dominatee.
1908bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
1909 const MemoryAccess *Dominatee) const {
Sebastian Pope1f60b12016-06-10 21:36:41 +00001910
Daniel Berlin5c46b942016-07-19 22:49:43 +00001911 const BasicBlock *DominatorBlock = Dominator->getBlock();
Daniel Berlin5c46b942016-07-19 22:49:43 +00001912
Daniel Berlin19860302016-07-19 23:08:08 +00001913 assert((DominatorBlock == Dominatee->getBlock()) &&
Daniel Berlin5c46b942016-07-19 22:49:43 +00001914 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00001915 // A node dominates itself.
1916 if (Dominatee == Dominator)
1917 return true;
1918
1919 // When Dominatee is defined on function entry, it is not dominated by another
1920 // memory access.
1921 if (isLiveOnEntryDef(Dominatee))
1922 return false;
1923
1924 // When Dominator is defined on function entry, it dominates the other memory
1925 // access.
1926 if (isLiveOnEntryDef(Dominator))
1927 return true;
1928
Daniel Berlin5c46b942016-07-19 22:49:43 +00001929 if (!BlockNumberingValid.count(DominatorBlock))
1930 renumberBlock(DominatorBlock);
George Burgess IVe1100f52016-02-02 22:46:49 +00001931
Daniel Berlin5c46b942016-07-19 22:49:43 +00001932 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
1933 // All numbers start with 1
1934 assert(DominatorNum != 0 && "Block was not numbered properly");
1935 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
1936 assert(DominateeNum != 0 && "Block was not numbered properly");
1937 return DominatorNum < DominateeNum;
George Burgess IVe1100f52016-02-02 22:46:49 +00001938}
1939
George Burgess IV5f308972016-07-19 01:29:15 +00001940bool MemorySSA::dominates(const MemoryAccess *Dominator,
1941 const MemoryAccess *Dominatee) const {
1942 if (Dominator == Dominatee)
1943 return true;
1944
1945 if (isLiveOnEntryDef(Dominatee))
1946 return false;
1947
1948 if (Dominator->getBlock() != Dominatee->getBlock())
1949 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
1950 return locallyDominates(Dominator, Dominatee);
1951}
1952
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001953bool MemorySSA::dominates(const MemoryAccess *Dominator,
1954 const Use &Dominatee) const {
1955 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
1956 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
1957 // The def must dominate the incoming block of the phi.
1958 if (UseBB != Dominator->getBlock())
1959 return DT->dominates(Dominator->getBlock(), UseBB);
1960 // If the UseBB and the DefBB are the same, compare locally.
1961 return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
1962 }
1963 // If it's not a PHI node use, the normal dominates can already handle it.
1964 return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
1965}
1966
George Burgess IVe1100f52016-02-02 22:46:49 +00001967const static char LiveOnEntryStr[] = "liveOnEntry";
1968
1969void MemoryDef::print(raw_ostream &OS) const {
1970 MemoryAccess *UO = getDefiningAccess();
1971
1972 OS << getID() << " = MemoryDef(";
1973 if (UO && UO->getID())
1974 OS << UO->getID();
1975 else
1976 OS << LiveOnEntryStr;
1977 OS << ')';
1978}
1979
1980void MemoryPhi::print(raw_ostream &OS) const {
1981 bool First = true;
1982 OS << getID() << " = MemoryPhi(";
1983 for (const auto &Op : operands()) {
1984 BasicBlock *BB = getIncomingBlock(Op);
1985 MemoryAccess *MA = cast<MemoryAccess>(Op);
1986 if (!First)
1987 OS << ',';
1988 else
1989 First = false;
1990
1991 OS << '{';
1992 if (BB->hasName())
1993 OS << BB->getName();
1994 else
1995 BB->printAsOperand(OS, false);
1996 OS << ',';
1997 if (unsigned ID = MA->getID())
1998 OS << ID;
1999 else
2000 OS << LiveOnEntryStr;
2001 OS << '}';
2002 }
2003 OS << ')';
2004}
2005
2006MemoryAccess::~MemoryAccess() {}
2007
2008void MemoryUse::print(raw_ostream &OS) const {
2009 MemoryAccess *UO = getDefiningAccess();
2010 OS << "MemoryUse(";
2011 if (UO && UO->getID())
2012 OS << UO->getID();
2013 else
2014 OS << LiveOnEntryStr;
2015 OS << ')';
2016}
2017
2018void MemoryAccess::dump() const {
2019 print(dbgs());
2020 dbgs() << "\n";
2021}
2022
Chad Rosier232e29e2016-07-06 21:20:47 +00002023char MemorySSAPrinterLegacyPass::ID = 0;
2024
2025MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
2026 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
2027}
2028
2029void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
2030 AU.setPreservesAll();
2031 AU.addRequired<MemorySSAWrapperPass>();
2032 AU.addPreserved<MemorySSAWrapperPass>();
2033}
2034
2035bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
2036 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2037 MSSA.print(dbgs());
2038 if (VerifyMemorySSA)
2039 MSSA.verifyMemorySSA();
2040 return false;
2041}
2042
Geoff Berryb96d3b22016-06-01 21:30:40 +00002043char MemorySSAAnalysis::PassID;
George Burgess IVe1100f52016-02-02 22:46:49 +00002044
Daniel Berlin1e98c042016-09-26 17:22:54 +00002045MemorySSAAnalysis::Result MemorySSAAnalysis::run(Function &F,
2046 FunctionAnalysisManager &AM) {
Geoff Berryb96d3b22016-06-01 21:30:40 +00002047 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2048 auto &AA = AM.getResult<AAManager>(F);
Geoff Berry290a13e2016-08-08 18:27:22 +00002049 return MemorySSAAnalysis::Result(make_unique<MemorySSA>(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002050}
2051
Geoff Berryb96d3b22016-06-01 21:30:40 +00002052PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
2053 FunctionAnalysisManager &AM) {
2054 OS << "MemorySSA for function: " << F.getName() << "\n";
Geoff Berry290a13e2016-08-08 18:27:22 +00002055 AM.getResult<MemorySSAAnalysis>(F).getMSSA().print(OS);
Geoff Berryb96d3b22016-06-01 21:30:40 +00002056
2057 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00002058}
2059
Geoff Berryb96d3b22016-06-01 21:30:40 +00002060PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
2061 FunctionAnalysisManager &AM) {
Geoff Berry290a13e2016-08-08 18:27:22 +00002062 AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002063
2064 return PreservedAnalyses::all();
2065}
2066
2067char MemorySSAWrapperPass::ID = 0;
2068
2069MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
2070 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
2071}
2072
2073void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
2074
2075void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002076 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002077 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
2078 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00002079}
2080
Geoff Berryb96d3b22016-06-01 21:30:40 +00002081bool MemorySSAWrapperPass::runOnFunction(Function &F) {
2082 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2083 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2084 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002085 return false;
2086}
2087
Geoff Berryb96d3b22016-06-01 21:30:40 +00002088void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00002089
Geoff Berryb96d3b22016-06-01 21:30:40 +00002090void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002091 MSSA->print(OS);
2092}
2093
George Burgess IVe1100f52016-02-02 22:46:49 +00002094MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
2095
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002096MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A,
2097 DominatorTree *D)
Daniel Berlin5c46b942016-07-19 22:49:43 +00002098 : MemorySSAWalker(M), Walker(*M, *A, *D, Cache), AutoResetWalker(true) {}
George Burgess IVe1100f52016-02-02 22:46:49 +00002099
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002100MemorySSA::CachingWalker::~CachingWalker() {}
George Burgess IVe1100f52016-02-02 22:46:49 +00002101
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002102void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) {
Daniel Berlin83fc77b2016-03-01 18:46:54 +00002103 // TODO: We can do much better cache invalidation with differently stored
2104 // caches. For now, for MemoryUses, we simply remove them
2105 // from the cache, and kill the entire call/non-call cache for everything
2106 // else. The problem is for phis or defs, currently we'd need to follow use
2107 // chains down and invalidate anything below us in the chain that currently
2108 // terminates at this access.
2109
2110 // See if this is a MemoryUse, if so, just remove the cached info. MemoryUse
2111 // is by definition never a barrier, so nothing in the cache could point to
2112 // this use. In that case, we only need invalidate the info for the use
2113 // itself.
2114
2115 if (MemoryUse *MU = dyn_cast<MemoryUse>(MA)) {
George Burgess IV5f308972016-07-19 01:29:15 +00002116 UpwardsMemoryQuery Q(MU->getMemoryInst(), MU);
2117 Cache.remove(MU, Q.StartingLoc, Q.IsCall);
Geoff Berry9fe26e62016-04-22 14:44:10 +00002118 } else {
2119 // 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 +00002120 Cache.clear();
Geoff Berry9fe26e62016-04-22 14:44:10 +00002121 }
2122
Filipe Cabecinhas0da99372016-04-29 15:22:48 +00002123#ifdef EXPENSIVE_CHECKS
Geoff Berry9fe26e62016-04-22 14:44:10 +00002124 verifyRemoved(MA);
2125#endif
Daniel Berlin83fc77b2016-03-01 18:46:54 +00002126}
2127
George Burgess IVe1100f52016-02-02 22:46:49 +00002128/// \brief Walk the use-def chains starting at \p MA and find
2129/// the MemoryAccess that actually clobbers Loc.
2130///
2131/// \returns our clobbering memory access
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002132MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
2133 MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +00002134 MemoryAccess *New = Walker.findClobber(StartingAccess, Q);
2135#ifdef EXPENSIVE_CHECKS
2136 MemoryAccess *NewNoCache =
2137 Walker.findClobber(StartingAccess, Q, /*UseWalkerCache=*/false);
2138 assert(NewNoCache == New && "Cache made us hand back a different result?");
2139#endif
2140 if (AutoResetWalker)
2141 resetClobberWalker();
2142 return New;
George Burgess IVe1100f52016-02-02 22:46:49 +00002143}
2144
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002145MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
2146 MemoryAccess *StartingAccess, MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002147 if (isa<MemoryPhi>(StartingAccess))
2148 return StartingAccess;
2149
2150 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
2151 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
2152 return StartingUseOrDef;
2153
2154 Instruction *I = StartingUseOrDef->getMemoryInst();
2155
2156 // Conservatively, fences are always clobbers, so don't perform the walk if we
2157 // hit a fence.
David Majnemera940f362016-07-15 17:19:24 +00002158 if (!ImmutableCallSite(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002159 return StartingUseOrDef;
2160
2161 UpwardsMemoryQuery Q;
2162 Q.OriginalAccess = StartingUseOrDef;
2163 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00002164 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00002165 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00002166
George Burgess IV5f308972016-07-19 01:29:15 +00002167 if (auto *CacheResult = Cache.lookup(StartingUseOrDef, Loc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00002168 return CacheResult;
2169
2170 // Unlike the other function, do not walk to the def of a def, because we are
2171 // handed something we already believe is the clobbering access.
2172 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
2173 ? StartingUseOrDef->getDefiningAccess()
2174 : StartingUseOrDef;
2175
2176 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002177 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2178 DEBUG(dbgs() << *StartingUseOrDef << "\n");
2179 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2180 DEBUG(dbgs() << *Clobber << "\n");
2181 return Clobber;
2182}
2183
2184MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002185MemorySSA::CachingWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
2186 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2187 // If this is a MemoryPhi, we can't do anything.
2188 if (!StartingAccess)
2189 return MA;
George Burgess IVe1100f52016-02-02 22:46:49 +00002190
George Burgess IV400ae402016-07-20 19:51:34 +00002191 const Instruction *I = StartingAccess->getMemoryInst();
George Burgess IV5f308972016-07-19 01:29:15 +00002192 UpwardsMemoryQuery Q(I, StartingAccess);
David Majnemera940f362016-07-15 17:19:24 +00002193 // We can't sanely do anything with a fences, they conservatively
George Burgess IVe1100f52016-02-02 22:46:49 +00002194 // clobber all memory, and have no locations to get pointers from to
David Majnemera940f362016-07-15 17:19:24 +00002195 // try to disambiguate.
George Burgess IV5f308972016-07-19 01:29:15 +00002196 if (!Q.IsCall && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002197 return StartingAccess;
2198
George Burgess IV5f308972016-07-19 01:29:15 +00002199 if (auto *CacheResult = Cache.lookup(StartingAccess, Q.StartingLoc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00002200 return CacheResult;
2201
George Burgess IV024f3d22016-08-03 19:57:02 +00002202 if (isUseTriviallyOptimizableToLiveOnEntry(*MSSA->AA, I)) {
2203 MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
2204 Cache.insert(StartingAccess, LiveOnEntry, Q.StartingLoc, Q.IsCall);
2205 return LiveOnEntry;
2206 }
2207
George Burgess IVe1100f52016-02-02 22:46:49 +00002208 // Start with the thing we already think clobbers this location
2209 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2210
2211 // At this point, DefiningAccess may be the live on entry def.
2212 // If it is, we will not get a better result.
2213 if (MSSA->isLiveOnEntryDef(DefiningAccess))
2214 return DefiningAccess;
2215
2216 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002217 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2218 DEBUG(dbgs() << *DefiningAccess << "\n");
2219 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2220 DEBUG(dbgs() << *Result << "\n");
2221
2222 return Result;
2223}
2224
Geoff Berry9fe26e62016-04-22 14:44:10 +00002225// Verify that MA doesn't exist in any of the caches.
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002226void MemorySSA::CachingWalker::verifyRemoved(MemoryAccess *MA) {
George Burgess IV5f308972016-07-19 01:29:15 +00002227 assert(!Cache.contains(MA) && "Found removed MemoryAccess in cache.");
Geoff Berry9fe26e62016-04-22 14:44:10 +00002228}
2229
George Burgess IVe1100f52016-02-02 22:46:49 +00002230MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002231DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002232 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2233 return Use->getDefiningAccess();
2234 return MA;
2235}
2236
2237MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
2238 MemoryAccess *StartingAccess, MemoryLocation &) {
2239 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2240 return Use->getDefiningAccess();
2241 return StartingAccess;
2242}
George Burgess IV5f308972016-07-19 01:29:15 +00002243} // namespace llvm