blob: c10979c8bb8cf45d0439d730105f5db9d0150c27 [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
64static cl::opt<bool>
65 VerifyMemorySSA("verify-memoryssa", cl::init(false), cl::Hidden,
66 cl::desc("Verify MemorySSA in legacy printer pass."));
67
George Burgess IVe1100f52016-02-02 22:46:49 +000068namespace llvm {
George Burgess IVe1100f52016-02-02 22:46:49 +000069/// \brief An assembly annotator class to print Memory SSA information in
70/// comments.
71class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
72 friend class MemorySSA;
73 const MemorySSA *MSSA;
74
75public:
76 MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
77
78 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
79 formatted_raw_ostream &OS) {
80 if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
81 OS << "; " << *MA << "\n";
82 }
83
84 virtual void emitInstructionAnnot(const Instruction *I,
85 formatted_raw_ostream &OS) {
86 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
87 OS << "; " << *MA << "\n";
88 }
89};
George Burgess IV5f308972016-07-19 01:29:15 +000090}
George Burgess IVfd1f2f82016-06-24 21:02:12 +000091
George Burgess IV5f308972016-07-19 01:29:15 +000092namespace {
93struct UpwardsMemoryQuery {
94 // True if our original query started off as a call
95 bool IsCall;
96 // The pointer location we started the query with. This will be empty if
97 // IsCall is true.
98 MemoryLocation StartingLoc;
99 // This is the instruction we were querying about.
100 const Instruction *Inst;
101 // The MemoryAccess we actually got called with, used to test local domination
102 const MemoryAccess *OriginalAccess;
103
104 UpwardsMemoryQuery()
105 : IsCall(false), Inst(nullptr), OriginalAccess(nullptr) {}
106
107 UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
108 : IsCall(ImmutableCallSite(Inst)), Inst(Inst), OriginalAccess(Access) {
109 if (!IsCall)
110 StartingLoc = MemoryLocation::get(Inst);
111 }
112};
113
114static bool instructionClobbersQuery(MemoryDef *MD, const MemoryLocation &Loc,
115 const UpwardsMemoryQuery &Query,
116 AliasAnalysis &AA) {
117 Instruction *DefMemoryInst = MD->getMemoryInst();
118 assert(DefMemoryInst && "Defining instruction not actually an instruction");
119
120 if (!Query.IsCall)
121 return AA.getModRefInfo(DefMemoryInst, Loc) & MRI_Mod;
122
123 ModRefInfo I = AA.getModRefInfo(DefMemoryInst, ImmutableCallSite(Query.Inst));
124 return I != MRI_NoModRef;
125}
126
127/// Cache for our caching MemorySSA walker.
128class WalkerCache {
129 DenseMap<ConstMemoryAccessPair, MemoryAccess *> Accesses;
130 DenseMap<const MemoryAccess *, MemoryAccess *> Calls;
131
132public:
133 MemoryAccess *lookup(const MemoryAccess *MA, const MemoryLocation &Loc,
134 bool IsCall) const {
135 ++NumClobberCacheLookups;
136 MemoryAccess *R = IsCall ? Calls.lookup(MA) : Accesses.lookup({MA, Loc});
137 if (R)
138 ++NumClobberCacheHits;
139 return R;
140 }
141
142 bool insert(const MemoryAccess *MA, MemoryAccess *To,
143 const MemoryLocation &Loc, bool IsCall) {
144 // This is fine for Phis, since there are times where we can't optimize
145 // them. Making a def its own clobber is never correct, though.
146 assert((MA != To || isa<MemoryPhi>(MA)) &&
147 "Something can't clobber itself!");
148
149 ++NumClobberCacheInserts;
150 bool Inserted;
151 if (IsCall)
152 Inserted = Calls.insert({MA, To}).second;
153 else
154 Inserted = Accesses.insert({{MA, Loc}, To}).second;
155
156 return Inserted;
157 }
158
159 bool remove(const MemoryAccess *MA, const MemoryLocation &Loc, bool IsCall) {
160 return IsCall ? Calls.erase(MA) : Accesses.erase({MA, Loc});
161 }
162
163 void clear() {
164 Accesses.clear();
165 Calls.clear();
166 }
167
168 bool contains(const MemoryAccess *MA) const {
169 for (auto &P : Accesses)
170 if (P.first.first == MA || P.second == MA)
171 return true;
172 for (auto &P : Calls)
173 if (P.first == MA || P.second == MA)
174 return true;
175 return false;
176 }
177};
178
179/// Walks the defining uses of MemoryDefs. Stops after we hit something that has
180/// no defining use (e.g. a MemoryPhi or liveOnEntry). Note that, when comparing
181/// against a null def_chain_iterator, this will compare equal only after
182/// walking said Phi/liveOnEntry.
183struct def_chain_iterator
184 : public iterator_facade_base<def_chain_iterator, std::forward_iterator_tag,
185 MemoryAccess *> {
186 def_chain_iterator() : MA(nullptr) {}
187 def_chain_iterator(MemoryAccess *MA) : MA(MA) {}
188
189 MemoryAccess *operator*() const { return MA; }
190
191 def_chain_iterator &operator++() {
192 // N.B. liveOnEntry has a null defining access.
193 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
194 MA = MUD->getDefiningAccess();
195 else
196 MA = nullptr;
197 return *this;
198 }
199
200 bool operator==(const def_chain_iterator &O) const { return MA == O.MA; }
201
202private:
203 MemoryAccess *MA;
204};
205
206static iterator_range<def_chain_iterator>
207def_chain(MemoryAccess *MA, MemoryAccess *UpTo = nullptr) {
208#ifdef EXPENSIVE_CHECKS
209 assert((!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator()) &&
210 "UpTo isn't in the def chain!");
211#endif
212 return make_range(def_chain_iterator(MA), def_chain_iterator(UpTo));
213}
214
215/// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
216/// inbetween `Start` and `ClobberAt` can clobbers `Start`.
217///
218/// This is meant to be as simple and self-contained as possible. Because it
219/// uses no cache, etc., it can be relatively expensive.
220///
221/// \param Start The MemoryAccess that we want to walk from.
222/// \param ClobberAt A clobber for Start.
223/// \param StartLoc The MemoryLocation for Start.
224/// \param MSSA The MemorySSA isntance that Start and ClobberAt belong to.
225/// \param Query The UpwardsMemoryQuery we used for our search.
226/// \param AA The AliasAnalysis we used for our search.
227static void LLVM_ATTRIBUTE_UNUSED
228checkClobberSanity(MemoryAccess *Start, MemoryAccess *ClobberAt,
229 const MemoryLocation &StartLoc, const MemorySSA &MSSA,
230 const UpwardsMemoryQuery &Query, AliasAnalysis &AA) {
231 assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
232
233 if (MSSA.isLiveOnEntryDef(Start)) {
234 assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
235 "liveOnEntry must clobber itself");
236 return;
237 }
238
239 assert((isa<MemoryPhi>(Start) || Start != ClobberAt) &&
240 "Start can't clobber itself!");
241
242 bool FoundClobber = false;
243 DenseSet<MemoryAccessPair> VisitedPhis;
244 SmallVector<MemoryAccessPair, 8> Worklist;
245 Worklist.emplace_back(Start, StartLoc);
246 // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
247 // is found, complain.
248 while (!Worklist.empty()) {
249 MemoryAccessPair MAP = Worklist.pop_back_val();
250 // All we care about is that nothing from Start to ClobberAt clobbers Start.
251 // We learn nothing from revisiting nodes.
252 if (!VisitedPhis.insert(MAP).second)
253 continue;
254
255 for (MemoryAccess *MA : def_chain(MAP.first)) {
256 if (MA == ClobberAt) {
257 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
258 // instructionClobbersQuery isn't essentially free, so don't use `|=`,
259 // since it won't let us short-circuit.
260 //
261 // Also, note that this can't be hoisted out of the `Worklist` loop,
262 // since MD may only act as a clobber for 1 of N MemoryLocations.
263 FoundClobber = FoundClobber || MSSA.isLiveOnEntryDef(MD) ||
264 instructionClobbersQuery(MD, MAP.second, Query, AA);
265 }
266 break;
267 }
268
269 // We should never hit liveOnEntry, unless it's the clobber.
270 assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
271
272 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
273 (void)MD;
274 assert(!instructionClobbersQuery(MD, MAP.second, Query, AA) &&
275 "Found clobber before reaching ClobberAt!");
276 continue;
277 }
278
279 assert(isa<MemoryPhi>(MA));
280 Worklist.append(upward_defs_begin({MA, MAP.second}), upward_defs_end());
281 }
282 }
283
284 // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
285 // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
286 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
287 "ClobberAt never acted as a clobber");
288}
289
290/// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
291/// in one class.
292class ClobberWalker {
293 /// Save a few bytes by using unsigned instead of size_t.
294 using ListIndex = unsigned;
295
296 /// Represents a span of contiguous MemoryDefs, potentially ending in a
297 /// MemoryPhi.
298 struct DefPath {
299 MemoryLocation Loc;
300 // Note that, because we always walk in reverse, Last will always dominate
301 // First. Also note that First and Last are inclusive.
302 MemoryAccess *First;
303 MemoryAccess *Last;
304 // N.B. Blocker is currently basically unused. The goal is to use it to make
305 // cache invalidation better, but we're not there yet.
306 MemoryAccess *Blocker;
307 Optional<ListIndex> Previous;
308
309 DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
310 Optional<ListIndex> Previous)
311 : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
312
313 DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
314 Optional<ListIndex> Previous)
315 : DefPath(Loc, Init, Init, Previous) {}
316 };
317
318 const MemorySSA &MSSA;
319 AliasAnalysis &AA;
320 DominatorTree &DT;
321 WalkerCache &WC;
322 UpwardsMemoryQuery *Query;
323 bool UseCache;
324
325 // Phi optimization bookkeeping
326 SmallVector<DefPath, 32> Paths;
327 DenseSet<ConstMemoryAccessPair> VisitedPhis;
328 DenseMap<const BasicBlock *, MemoryAccess *> WalkTargetCache;
329
330 void setUseCache(bool Use) { UseCache = Use; }
331 bool shouldIgnoreCache() const {
332 // UseCache will only be false when we're debugging, or when expensive
333 // checks are enabled. In either case, we don't care deeply about speed.
334 return LLVM_UNLIKELY(!UseCache);
335 }
336
337 void addCacheEntry(const MemoryAccess *What, MemoryAccess *To,
338 const MemoryLocation &Loc) const {
339// EXPENSIVE_CHECKS because most of these queries are redundant, and if What
340// and To are in the same BB, that gives us n^2 behavior.
341#ifdef EXPENSIVE_CHECKS
342 assert(MSSA.dominates(To, What));
343#endif
344 if (shouldIgnoreCache())
345 return;
346 WC.insert(What, To, Loc, Query->IsCall);
347 }
348
349 MemoryAccess *lookupCache(const MemoryAccess *MA, const MemoryLocation &Loc) {
350 return shouldIgnoreCache() ? nullptr : WC.lookup(MA, Loc, Query->IsCall);
351 }
352
353 void cacheDefPath(const DefPath &DN, MemoryAccess *Target) const {
354 if (shouldIgnoreCache())
355 return;
356
357 for (MemoryAccess *MA : def_chain(DN.First, DN.Last))
358 addCacheEntry(MA, Target, DN.Loc);
359
360 // DefPaths only express the path we walked. So, DN.Last could either be a
361 // thing we want to cache, or not.
362 if (DN.Last != Target)
363 addCacheEntry(DN.Last, Target, DN.Loc);
364 }
365
366 /// Find the nearest def or phi that `From` can legally be optimized to.
367 ///
368 /// FIXME: Deduplicate this with MSSA::findDominatingDef. Ideally, MSSA should
369 /// keep track of this information for us, and allow us O(1) lookups of this
370 /// info.
371 MemoryAccess *getWalkTarget(const MemoryPhi *From) {
372 assert(!MSSA.isLiveOnEntryDef(From) && "liveOnEntry has no target.");
373 assert(From->getNumOperands() && "Phi with no operands?");
374
375 BasicBlock *BB = From->getBlock();
376 auto At = WalkTargetCache.find(BB);
377 if (At != WalkTargetCache.end())
378 return At->second;
379
380 SmallVector<const BasicBlock *, 8> ToCache;
381 ToCache.push_back(BB);
382
383 MemoryAccess *Result = MSSA.getLiveOnEntryDef();
384 DomTreeNode *Node = DT.getNode(BB);
385 while ((Node = Node->getIDom())) {
386 auto At = WalkTargetCache.find(BB);
387 if (At != WalkTargetCache.end()) {
388 Result = At->second;
389 break;
390 }
391
392 auto *Accesses = MSSA.getBlockAccesses(Node->getBlock());
393 if (Accesses) {
394 auto Iter = find_if(reverse(*Accesses), [](const MemoryAccess &MA) {
395 return !isa<MemoryUse>(MA);
396 });
397 if (Iter != Accesses->rend()) {
398 Result = const_cast<MemoryAccess *>(&*Iter);
399 break;
400 }
401 }
402
403 ToCache.push_back(Node->getBlock());
404 }
405
406 for (const BasicBlock *BB : ToCache)
407 WalkTargetCache.insert({BB, Result});
408 return Result;
409 }
410
411 /// Result of calling walkToPhiOrClobber.
412 struct UpwardsWalkResult {
413 /// The "Result" of the walk. Either a clobber, the last thing we walked, or
414 /// both.
415 MemoryAccess *Result;
416 bool IsKnownClobber;
417 bool FromCache;
418 };
419
420 /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
421 /// This will update Desc.Last as it walks. It will (optionally) also stop at
422 /// StopAt.
423 ///
424 /// This does not test for whether StopAt is a clobber
425 UpwardsWalkResult walkToPhiOrClobber(DefPath &Desc,
426 MemoryAccess *StopAt = nullptr) {
427 assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
428
429 for (MemoryAccess *Current : def_chain(Desc.Last)) {
430 Desc.Last = Current;
431 if (Current == StopAt)
432 return {Current, false, false};
433
434 if (auto *MD = dyn_cast<MemoryDef>(Current))
435 if (MSSA.isLiveOnEntryDef(MD) ||
436 instructionClobbersQuery(MD, Desc.Loc, *Query, AA))
437 return {MD, true, false};
438
439 // Cache checks must be done last, because if Current is a clobber, the
440 // cache will contain the clobber for Current.
441 if (MemoryAccess *MA = lookupCache(Current, Desc.Loc))
442 return {MA, true, true};
443 }
444
445 assert(isa<MemoryPhi>(Desc.Last) &&
446 "Ended at a non-clobber that's not a phi?");
447 return {Desc.Last, false, false};
448 }
449
450 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
451 ListIndex PriorNode) {
452 auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),
453 upward_defs_end());
454 for (const MemoryAccessPair &P : UpwardDefs) {
455 PausedSearches.push_back(Paths.size());
456 Paths.emplace_back(P.second, P.first, PriorNode);
457 }
458 }
459
460 /// Represents a search that terminated after finding a clobber. This clobber
461 /// may or may not be present in the path of defs from LastNode..SearchStart,
462 /// since it may have been retrieved from cache.
463 struct TerminatedPath {
464 MemoryAccess *Clobber;
465 ListIndex LastNode;
466 };
467
468 /// Get an access that keeps us from optimizing to the given phi.
469 ///
470 /// PausedSearches is an array of indices into the Paths array. Its incoming
471 /// value is the indices of searches that stopped at the last phi optimization
472 /// target. It's left in an unspecified state.
473 ///
474 /// If this returns None, NewPaused is a vector of searches that terminated
475 /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
476 Optional<ListIndex>
477 getBlockingAccess(MemoryAccess *StopWhere,
478 SmallVectorImpl<ListIndex> &PausedSearches,
479 SmallVectorImpl<ListIndex> &NewPaused,
480 SmallVectorImpl<TerminatedPath> &Terminated) {
481 assert(!PausedSearches.empty() && "No searches to continue?");
482
483 // BFS vs DFS really doesn't make a difference here, so just do a DFS with
484 // PausedSearches as our stack.
485 while (!PausedSearches.empty()) {
486 ListIndex PathIndex = PausedSearches.pop_back_val();
487 DefPath &Node = Paths[PathIndex];
488
489 // If we've already visited this path with this MemoryLocation, we don't
490 // need to do so again.
491 //
492 // NOTE: That we just drop these paths on the ground makes caching
493 // behavior sporadic. e.g. given a diamond:
494 // A
495 // B C
496 // D
497 //
498 // ...If we walk D, B, A, C, we'll only cache the result of phi
499 // optimization for A, B, and D; C will be skipped because it dies here.
500 // This arguably isn't the worst thing ever, since:
501 // - We generally query things in a top-down order, so if we got below D
502 // without needing cache entries for {C, MemLoc}, then chances are
503 // that those cache entries would end up ultimately unused.
504 // - We still cache things for A, so C only needs to walk up a bit.
505 // If this behavior becomes problematic, we can fix without a ton of extra
506 // work.
507 if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
508 continue;
509
510 UpwardsWalkResult Res = walkToPhiOrClobber(Node, /*StopAt=*/StopWhere);
511 if (Res.IsKnownClobber) {
512 assert(Res.Result != StopWhere || Res.FromCache);
513 // If this wasn't a cache hit, we hit a clobber when walking. That's a
514 // failure.
515 if (!Res.FromCache || !MSSA.dominates(Res.Result, StopWhere))
516 return PathIndex;
517
518 // Otherwise, it's a valid thing to potentially optimize to.
519 Terminated.push_back({Res.Result, PathIndex});
520 continue;
521 }
522
523 if (Res.Result == StopWhere) {
524 // We've hit our target. Save this path off for if we want to continue
525 // walking.
526 NewPaused.push_back(PathIndex);
527 continue;
528 }
529
530 assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
531 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
532 }
533
534 return None;
535 }
536
537 template <typename T, typename Walker>
538 struct generic_def_path_iterator
539 : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
540 std::forward_iterator_tag, T *> {
541 generic_def_path_iterator() : W(nullptr), N(None) {}
542 generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
543
544 T &operator*() const { return curNode(); }
545
546 generic_def_path_iterator &operator++() {
547 N = curNode().Previous;
548 return *this;
549 }
550
551 bool operator==(const generic_def_path_iterator &O) const {
552 if (N.hasValue() != O.N.hasValue())
553 return false;
554 return !N.hasValue() || *N == *O.N;
555 }
556
557 private:
558 T &curNode() const { return W->Paths[*N]; }
559
560 Walker *W;
561 Optional<ListIndex> N;
562 };
563
564 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
565 using const_def_path_iterator =
566 generic_def_path_iterator<const DefPath, const ClobberWalker>;
567
568 iterator_range<def_path_iterator> def_path(ListIndex From) {
569 return make_range(def_path_iterator(this, From), def_path_iterator());
570 }
571
572 iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
573 return make_range(const_def_path_iterator(this, From),
574 const_def_path_iterator());
575 }
576
577 struct OptznResult {
578 /// The path that contains our result.
579 TerminatedPath PrimaryClobber;
580 /// The paths that we can legally cache back from, but that aren't
581 /// necessarily the result of the Phi optimization.
582 SmallVector<TerminatedPath, 4> OtherClobbers;
583 };
584
585 ListIndex defPathIndex(const DefPath &N) const {
586 // The assert looks nicer if we don't need to do &N
587 const DefPath *NP = &N;
588 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
589 "Out of bounds DefPath!");
590 return NP - &Paths.front();
591 }
592
593 /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
594 /// that act as legal clobbers. Note that this won't return *all* clobbers.
595 ///
596 /// Phi optimization algorithm tl;dr:
597 /// - Find the earliest def/phi, A, we can optimize to
598 /// - Find if all paths from the starting memory access ultimately reach A
599 /// - If not, optimization isn't possible.
600 /// - Otherwise, walk from A to another clobber or phi, A'.
601 /// - If A' is a def, we're done.
602 /// - If A' is a phi, try to optimize it.
603 ///
604 /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
605 /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
606 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
607 const MemoryLocation &Loc) {
608 assert(Paths.empty() && VisitedPhis.empty() &&
609 "Reset the optimization state.");
610
611 Paths.emplace_back(Loc, Start, Phi, None);
612 // Stores how many "valid" optimization nodes we had prior to calling
613 // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
614 auto PriorPathsSize = Paths.size();
615
616 SmallVector<ListIndex, 16> PausedSearches;
617 SmallVector<ListIndex, 8> NewPaused;
618 SmallVector<TerminatedPath, 4> TerminatedPaths;
619
620 addSearches(Phi, PausedSearches, 0);
621
622 // Moves the TerminatedPath with the "most dominated" Clobber to the end of
623 // Paths.
624 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
625 assert(!Paths.empty() && "Need a path to move");
626 // FIXME: This is technically n^2 (n = distance(DefPath.First,
627 // DefPath.Last)) because of local dominance checks.
628 auto Dom = Paths.begin();
629 for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
630 if (!MSSA.dominates(I->Clobber, Dom->Clobber))
631 Dom = I;
632 auto Last = Paths.end() - 1;
633 if (Last != Dom)
634 std::iter_swap(Last, Dom);
635 };
636
637 MemoryPhi *Current = Phi;
638 while (1) {
639 assert(!MSSA.isLiveOnEntryDef(Current) &&
640 "liveOnEntry wasn't treated as a clobber?");
641
642 MemoryAccess *Target = getWalkTarget(Current);
643 // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
644 // optimization for the prior phi.
645 assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
646 return MSSA.dominates(P.Clobber, Target);
647 }));
648
649 // FIXME: This is broken, because the Blocker may be reported to be
650 // liveOnEntry, and we'll happily wait for that to disappear (read: never)
651 // For the moment, this is fine, since we do basically nothing with
652 // blocker info.
653 if (Optional<ListIndex> Blocker = getBlockingAccess(
654 Target, PausedSearches, NewPaused, TerminatedPaths)) {
655 MemoryAccess *BlockingAccess = Paths[*Blocker].Last;
656 // Cache our work on the blocking node, since we know that's correct.
657 cacheDefPath(Paths[*Blocker], BlockingAccess);
658
659 // Find the node we started at. We can't search based on N->Last, since
660 // we may have gone around a loop with a different MemoryLocation.
661 auto Iter = find_if(def_path(*Blocker), [&](const DefPath &N) {
662 return defPathIndex(N) < PriorPathsSize;
663 });
664 assert(Iter != def_path_iterator());
665
666 DefPath &CurNode = *Iter;
667 assert(CurNode.Last == Current);
668 CurNode.Blocker = BlockingAccess;
669
670 // Two things:
671 // A. We can't reliably cache all of NewPaused back. Consider a case
672 // where we have two paths in NewPaused; one of which can't optimize
673 // above this phi, whereas the other can. If we cache the second path
674 // back, we'll end up with suboptimal cache entries. We can handle
675 // cases like this a bit better when we either try to find all
676 // clobbers that block phi optimization, or when our cache starts
677 // supporting unfinished searches.
678 // B. We can't reliably cache TerminatedPaths back here without doing
679 // extra checks; consider a case like:
680 // T
681 // / \
682 // D C
683 // \ /
684 // S
685 // Where T is our target, C is a node with a clobber on it, D is a
686 // diamond (with a clobber *only* on the left or right node, N), and
687 // S is our start. Say we walk to D, through the node opposite N
688 // (read: ignoring the clobber), and see a cache entry in the top
689 // node of D. That cache entry gets put into TerminatedPaths. We then
690 // walk up to C (N is later in our worklist), find the clobber, and
691 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
692 // the bottom part of D to the cached clobber, ignoring the clobber
693 // in N. Again, this problem goes away if we start tracking all
694 // blockers for a given phi optimization.
695 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
696 return {Result, {}};
697 }
698
699 // If there's nothing left to search, then all paths led to valid clobbers
700 // that we got from our cache; pick the nearest to the start, and allow
701 // the rest to be cached back.
702 if (NewPaused.empty()) {
703 MoveDominatedPathToEnd(TerminatedPaths);
704 TerminatedPath Result = TerminatedPaths.pop_back_val();
705 return {Result, std::move(TerminatedPaths)};
706 }
707
708 MemoryAccess *DefChainEnd = nullptr;
709 SmallVector<TerminatedPath, 4> Clobbers;
710 for (ListIndex Paused : NewPaused) {
711 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
712 if (WR.IsKnownClobber)
713 Clobbers.push_back({WR.Result, Paused});
714 else
715 // Micro-opt: If we hit the end of the chain, save it.
716 DefChainEnd = WR.Result;
717 }
718
719 if (!TerminatedPaths.empty()) {
720 // If we couldn't find the dominating phi/liveOnEntry in the above loop,
721 // do it now.
722 if (!DefChainEnd)
723 for (MemoryAccess *MA : def_chain(Target))
724 DefChainEnd = MA;
725
726 // If any of the terminated paths don't dominate the phi we'll try to
727 // optimize, we need to figure out what they are and quit.
728 const BasicBlock *ChainBB = DefChainEnd->getBlock();
729 for (const TerminatedPath &TP : TerminatedPaths) {
730 // Because we know that DefChainEnd is as "high" as we can go, we
731 // don't need local dominance checks; BB dominance is sufficient.
732 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
733 Clobbers.push_back(TP);
734 }
735 }
736
737 // If we have clobbers in the def chain, find the one closest to Current
738 // and quit.
739 if (!Clobbers.empty()) {
740 MoveDominatedPathToEnd(Clobbers);
741 TerminatedPath Result = Clobbers.pop_back_val();
742 return {Result, std::move(Clobbers)};
743 }
744
745 assert(all_of(NewPaused,
746 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
747
748 // Because liveOnEntry is a clobber, this must be a phi.
749 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
750
751 PriorPathsSize = Paths.size();
752 PausedSearches.clear();
753 for (ListIndex I : NewPaused)
754 addSearches(DefChainPhi, PausedSearches, I);
755 NewPaused.clear();
756
757 Current = DefChainPhi;
758 }
759 }
760
761 /// Caches everything in an OptznResult.
762 void cacheOptResult(const OptznResult &R) {
763 if (R.OtherClobbers.empty()) {
764 // If we're not going to be caching OtherClobbers, don't bother with
765 // marking visited/etc.
766 for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode))
767 cacheDefPath(N, R.PrimaryClobber.Clobber);
768 return;
769 }
770
771 // PrimaryClobber is our answer. If we can cache anything back, we need to
772 // stop caching when we visit PrimaryClobber.
773 SmallBitVector Visited(Paths.size());
774 for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode)) {
775 Visited[defPathIndex(N)] = true;
776 cacheDefPath(N, R.PrimaryClobber.Clobber);
777 }
778
779 for (const TerminatedPath &P : R.OtherClobbers) {
780 for (const DefPath &N : const_def_path(P.LastNode)) {
781 ListIndex NIndex = defPathIndex(N);
782 if (Visited[NIndex])
783 break;
784 Visited[NIndex] = true;
785 cacheDefPath(N, P.Clobber);
786 }
787 }
788 }
789
790 void verifyOptResult(const OptznResult &R) const {
791 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
792 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
793 }));
794 }
795
796 void resetPhiOptznState() {
797 Paths.clear();
798 VisitedPhis.clear();
799 }
800
801public:
802 ClobberWalker(const MemorySSA &MSSA, AliasAnalysis &AA, DominatorTree &DT,
803 WalkerCache &WC)
804 : MSSA(MSSA), AA(AA), DT(DT), WC(WC), UseCache(true) {}
805
806 void reset() { WalkTargetCache.clear(); }
807
808 /// Finds the nearest clobber for the given query, optimizing phis if
809 /// possible.
810 MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q,
811 bool UseWalkerCache = true) {
812 setUseCache(UseWalkerCache);
813 Query = &Q;
814
815 MemoryAccess *Current = Start;
816 // This walker pretends uses don't exist. If we're handed one, silently grab
817 // its def. (This has the nice side-effect of ensuring we never cache uses)
818 if (auto *MU = dyn_cast<MemoryUse>(Start))
819 Current = MU->getDefiningAccess();
820
821 DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
822 // Fast path for the overly-common case (no crazy phi optimization
823 // necessary)
824 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
825 if (WalkResult.IsKnownClobber) {
826 cacheDefPath(FirstDesc, WalkResult.Result);
827 return WalkResult.Result;
828 }
829
830 OptznResult OptRes =
831 tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last), Current, Q.StartingLoc);
832 verifyOptResult(OptRes);
833 cacheOptResult(OptRes);
834 resetPhiOptznState();
835
836#ifdef EXPENSIVE_CHECKS
837 checkClobberSanity(Current, OptRes.PrimaryClobber.Clobber, Q.StartingLoc,
838 MSSA, Q, AA);
839#endif
840 return OptRes.PrimaryClobber.Clobber;
841 }
842};
843
844struct RenamePassData {
845 DomTreeNode *DTN;
846 DomTreeNode::const_iterator ChildIt;
847 MemoryAccess *IncomingVal;
848
849 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
850 MemoryAccess *M)
851 : DTN(D), ChildIt(It), IncomingVal(M) {}
852 void swap(RenamePassData &RHS) {
853 std::swap(DTN, RHS.DTN);
854 std::swap(ChildIt, RHS.ChildIt);
855 std::swap(IncomingVal, RHS.IncomingVal);
856 }
857};
858} // anonymous namespace
859
860namespace llvm {
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000861/// \brief A MemorySSAWalker that does AA walks and caching of lookups to
862/// disambiguate accesses.
863///
864/// FIXME: The current implementation of this can take quadratic space in rare
865/// cases. This can be fixed, but it is something to note until it is fixed.
866///
867/// In order to trigger this behavior, you need to store to N distinct locations
868/// (that AA can prove don't alias), perform M stores to other memory
869/// locations that AA can prove don't alias any of the initial N locations, and
870/// then load from all of the N locations. In this case, we insert M cache
871/// entries for each of the N loads.
872///
873/// For example:
874/// define i32 @foo() {
875/// %a = alloca i32, align 4
876/// %b = alloca i32, align 4
877/// store i32 0, i32* %a, align 4
878/// store i32 0, i32* %b, align 4
879///
880/// ; Insert M stores to other memory that doesn't alias %a or %b here
881///
882/// %c = load i32, i32* %a, align 4 ; Caches M entries in
883/// ; CachedUpwardsClobberingAccess for the
884/// ; MemoryLocation %a
885/// %d = load i32, i32* %b, align 4 ; Caches M entries in
886/// ; CachedUpwardsClobberingAccess for the
887/// ; MemoryLocation %b
888///
889/// ; For completeness' sake, loading %a or %b again would not cache *another*
890/// ; M entries.
891/// %r = add i32 %c, %d
892/// ret i32 %r
893/// }
894class MemorySSA::CachingWalker final : public MemorySSAWalker {
George Burgess IV5f308972016-07-19 01:29:15 +0000895 WalkerCache Cache;
896 ClobberWalker Walker;
897 bool AutoResetWalker;
898
899 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, UpwardsMemoryQuery &);
900 void verifyRemoved(MemoryAccess *);
901
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000902public:
903 CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *);
904 ~CachingWalker() override;
905
906 MemoryAccess *getClobberingMemoryAccess(const Instruction *) override;
907 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
908 MemoryLocation &) override;
909 void invalidateInfo(MemoryAccess *) override;
910
George Burgess IV5f308972016-07-19 01:29:15 +0000911 /// Whether we call resetClobberWalker() after each time we *actually* walk to
912 /// answer a clobber query.
913 void setAutoResetWalker(bool AutoReset) { AutoResetWalker = AutoReset; }
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000914
George Burgess IV5f308972016-07-19 01:29:15 +0000915 /// Drop the walker's persistent data structures. At the moment, this means
916 /// "drop the walker's cache of BasicBlocks ->
917 /// earliest-MemoryAccess-we-can-optimize-to". This is necessary if we're
918 /// going to have DT updates, if we remove MemoryAccesses, etc.
919 void resetClobberWalker() { Walker.reset(); }
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000920};
George Burgess IVe1100f52016-02-02 22:46:49 +0000921
George Burgess IVe1100f52016-02-02 22:46:49 +0000922/// \brief Rename a single basic block into MemorySSA form.
923/// Uses the standard SSA renaming algorithm.
924/// \returns The new incoming value.
925MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB,
926 MemoryAccess *IncomingVal) {
927 auto It = PerBlockAccesses.find(BB);
928 // Skip most processing if the list is empty.
929 if (It != PerBlockAccesses.end()) {
Daniel Berlinada263d2016-06-20 20:21:33 +0000930 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000931 for (MemoryAccess &L : *Accesses) {
932 switch (L.getValueID()) {
933 case Value::MemoryUseVal:
934 cast<MemoryUse>(&L)->setDefiningAccess(IncomingVal);
935 break;
936 case Value::MemoryDefVal:
937 // We can't legally optimize defs, because we only allow single
938 // memory phis/uses on operations, and if we optimize these, we can
939 // end up with multiple reaching defs. Uses do not have this
940 // problem, since they do not produce a value
941 cast<MemoryDef>(&L)->setDefiningAccess(IncomingVal);
942 IncomingVal = &L;
943 break;
944 case Value::MemoryPhiVal:
945 IncomingVal = &L;
946 break;
947 }
948 }
949 }
950
951 // Pass through values to our successors
952 for (const BasicBlock *S : successors(BB)) {
953 auto It = PerBlockAccesses.find(S);
954 // Rename the phi nodes in our successor block
955 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
956 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +0000957 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000958 auto *Phi = cast<MemoryPhi>(&Accesses->front());
George Burgess IVe1100f52016-02-02 22:46:49 +0000959 Phi->addIncoming(IncomingVal, BB);
960 }
961
962 return IncomingVal;
963}
964
965/// \brief This is the standard SSA renaming algorithm.
966///
967/// We walk the dominator tree in preorder, renaming accesses, and then filling
968/// in phi nodes in our successors.
969void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
970 SmallPtrSet<BasicBlock *, 16> &Visited) {
971 SmallVector<RenamePassData, 32> WorkStack;
972 IncomingVal = renameBlock(Root->getBlock(), IncomingVal);
973 WorkStack.push_back({Root, Root->begin(), IncomingVal});
974 Visited.insert(Root->getBlock());
975
976 while (!WorkStack.empty()) {
977 DomTreeNode *Node = WorkStack.back().DTN;
978 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
979 IncomingVal = WorkStack.back().IncomingVal;
980
981 if (ChildIt == Node->end()) {
982 WorkStack.pop_back();
983 } else {
984 DomTreeNode *Child = *ChildIt;
985 ++WorkStack.back().ChildIt;
986 BasicBlock *BB = Child->getBlock();
987 Visited.insert(BB);
988 IncomingVal = renameBlock(BB, IncomingVal);
989 WorkStack.push_back({Child, Child->begin(), IncomingVal});
990 }
991 }
992}
993
994/// \brief Compute dominator levels, used by the phi insertion algorithm above.
995void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) {
996 for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode());
997 DFI != DFE; ++DFI)
998 DomLevels[*DFI] = DFI.getPathLength() - 1;
999}
1000
George Burgess IVa362b092016-07-06 00:28:43 +00001001/// \brief This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +00001002/// unreachable blocks, and marking all other unreachable MemoryAccess's as
1003/// being uses of the live on entry definition.
1004void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
1005 assert(!DT->isReachableFromEntry(BB) &&
1006 "Reachable block found while handling unreachable blocks");
1007
Daniel Berlinfc7e6512016-07-06 05:32:05 +00001008 // Make sure phi nodes in our reachable successors end up with a
1009 // LiveOnEntryDef for our incoming edge, even though our block is forward
1010 // unreachable. We could just disconnect these blocks from the CFG fully,
1011 // but we do not right now.
1012 for (const BasicBlock *S : successors(BB)) {
1013 if (!DT->isReachableFromEntry(S))
1014 continue;
1015 auto It = PerBlockAccesses.find(S);
1016 // Rename the phi nodes in our successor block
1017 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1018 continue;
1019 AccessList *Accesses = It->second.get();
1020 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1021 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1022 }
1023
George Burgess IVe1100f52016-02-02 22:46:49 +00001024 auto It = PerBlockAccesses.find(BB);
1025 if (It == PerBlockAccesses.end())
1026 return;
1027
1028 auto &Accesses = It->second;
1029 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1030 auto Next = std::next(AI);
1031 // If we have a phi, just remove it. We are going to replace all
1032 // users with live on entry.
1033 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1034 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1035 else
1036 Accesses->erase(AI);
1037 AI = Next;
1038 }
1039}
1040
Geoff Berryb96d3b22016-06-01 21:30:40 +00001041MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
1042 : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
1043 NextID(0) {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001044 buildMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001045}
1046
1047MemorySSA::MemorySSA(MemorySSA &&MSSA)
1048 : AA(MSSA.AA), DT(MSSA.DT), F(MSSA.F),
1049 ValueToMemoryAccess(std::move(MSSA.ValueToMemoryAccess)),
1050 PerBlockAccesses(std::move(MSSA.PerBlockAccesses)),
1051 LiveOnEntryDef(std::move(MSSA.LiveOnEntryDef)),
1052 Walker(std::move(MSSA.Walker)), NextID(MSSA.NextID) {
1053 // Update the Walker MSSA pointer so it doesn't point to the moved-from MSSA
1054 // object any more.
1055 Walker->MSSA = this;
1056}
George Burgess IVe1100f52016-02-02 22:46:49 +00001057
1058MemorySSA::~MemorySSA() {
1059 // Drop all our references
1060 for (const auto &Pair : PerBlockAccesses)
1061 for (MemoryAccess &MA : *Pair.second)
1062 MA.dropAllReferences();
1063}
1064
Daniel Berlin14300262016-06-21 18:39:20 +00001065MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001066 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1067
1068 if (Res.second)
Daniel Berlinada263d2016-06-20 20:21:33 +00001069 Res.first->second = make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001070 return Res.first->second.get();
1071}
1072
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001073void MemorySSA::buildMemorySSA() {
George Burgess IVe1100f52016-02-02 22:46:49 +00001074 // We create an access to represent "live on entry", for things like
1075 // arguments or users of globals, where the memory they use is defined before
1076 // the beginning of the function. We do not actually insert it into the IR.
1077 // We do not define a live on exit for the immediate uses, and thus our
1078 // semantics do *not* imply that something with no immediate uses can simply
1079 // be removed.
1080 BasicBlock &StartingPoint = F.getEntryBlock();
1081 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
1082 &StartingPoint, NextID++);
1083
1084 // We maintain lists of memory accesses per-block, trading memory for time. We
1085 // could just look up the memory access for every possible instruction in the
1086 // stream.
1087 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001088 SmallPtrSet<BasicBlock *, 32> DefUseBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001089 // Go through each block, figure out where defs occur, and chain together all
1090 // the accesses.
1091 for (BasicBlock &B : F) {
Daniel Berlin7898ca62016-02-07 01:52:15 +00001092 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001093 AccessList *Accesses = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001094 for (Instruction &I : B) {
Peter Collingbourneffecb142016-05-26 01:19:17 +00001095 MemoryUseOrDef *MUD = createNewAccess(&I);
George Burgess IVb42b7622016-03-11 19:34:03 +00001096 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001097 continue;
George Burgess IV3887a412016-03-21 21:25:39 +00001098 InsertIntoDef |= isa<MemoryDef>(MUD);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001099
George Burgess IVe1100f52016-02-02 22:46:49 +00001100 if (!Accesses)
1101 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001102 Accesses->push_back(MUD);
George Burgess IVe1100f52016-02-02 22:46:49 +00001103 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001104 if (InsertIntoDef)
1105 DefiningBlocks.insert(&B);
George Burgess IV3887a412016-03-21 21:25:39 +00001106 if (Accesses)
Daniel Berlin1b51a292016-02-07 01:52:19 +00001107 DefUseBlocks.insert(&B);
1108 }
1109
1110 // Compute live-in.
1111 // Live in is normally defined as "all the blocks on the path from each def to
1112 // each of it's uses".
1113 // MemoryDef's are implicit uses of previous state, so they are also uses.
1114 // This means we don't really have def-only instructions. The only
1115 // MemoryDef's that are not really uses are those that are of the LiveOnEntry
1116 // variable (because LiveOnEntry can reach anywhere, and every def is a
1117 // must-kill of LiveOnEntry).
1118 // In theory, you could precisely compute live-in by using alias-analysis to
1119 // disambiguate defs and uses to see which really pair up with which.
1120 // In practice, this would be really expensive and difficult. So we simply
1121 // assume all defs are also uses that need to be kept live.
1122 // Because of this, the end result of this live-in computation will be "the
1123 // entire set of basic blocks that reach any use".
1124
1125 SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
1126 SmallVector<BasicBlock *, 64> LiveInBlockWorklist(DefUseBlocks.begin(),
1127 DefUseBlocks.end());
1128 // Now that we have a set of blocks where a value is live-in, recursively add
1129 // predecessors until we find the full region the value is live.
1130 while (!LiveInBlockWorklist.empty()) {
1131 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
1132
1133 // The block really is live in here, insert it into the set. If already in
1134 // the set, then it has already been processed.
1135 if (!LiveInBlocks.insert(BB).second)
1136 continue;
1137
1138 // Since the value is live into BB, it is either defined in a predecessor or
1139 // live into it to.
1140 LiveInBlockWorklist.append(pred_begin(BB), pred_end(BB));
George Burgess IVe1100f52016-02-02 22:46:49 +00001141 }
1142
1143 // Determine where our MemoryPhi's should go
Daniel Berlin77fa84e2016-04-19 06:13:28 +00001144 ForwardIDFCalculator IDFs(*DT);
George Burgess IVe1100f52016-02-02 22:46:49 +00001145 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001146 IDFs.setLiveInBlocks(LiveInBlocks);
George Burgess IVe1100f52016-02-02 22:46:49 +00001147 SmallVector<BasicBlock *, 32> IDFBlocks;
1148 IDFs.calculate(IDFBlocks);
1149
1150 // Now place MemoryPhi nodes.
1151 for (auto &BB : IDFBlocks) {
1152 // Insert phi node
Daniel Berlinada263d2016-06-20 20:21:33 +00001153 AccessList *Accesses = getOrCreateAccessList(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001154 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlinf6c9ae92016-02-10 17:41:25 +00001155 ValueToMemoryAccess.insert(std::make_pair(BB, Phi));
George Burgess IVe1100f52016-02-02 22:46:49 +00001156 // Phi's always are placed at the front of the block.
1157 Accesses->push_front(Phi);
1158 }
1159
1160 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1161 // filled in with all blocks.
1162 SmallPtrSet<BasicBlock *, 16> Visited;
1163 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1164
George Burgess IV5f308972016-07-19 01:29:15 +00001165 CachingWalker *Walker = getWalkerImpl();
1166
1167 // We're doing a batch of updates; don't drop useful caches between them.
1168 Walker->setAutoResetWalker(false);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001169
George Burgess IVe1100f52016-02-02 22:46:49 +00001170 // Now optimize the MemoryUse's defining access to point to the nearest
1171 // dominating clobbering def.
1172 // This ensures that MemoryUse's that are killed by the same store are
1173 // immediate users of that store, one of the invariants we guarantee.
1174 for (auto DomNode : depth_first(DT)) {
1175 BasicBlock *BB = DomNode->getBlock();
1176 auto AI = PerBlockAccesses.find(BB);
1177 if (AI == PerBlockAccesses.end())
1178 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +00001179 AccessList *Accesses = AI->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001180 for (auto &MA : *Accesses) {
1181 if (auto *MU = dyn_cast<MemoryUse>(&MA)) {
1182 Instruction *Inst = MU->getMemoryInst();
Daniel Berlin64120022016-03-02 21:16:28 +00001183 MU->setDefiningAccess(Walker->getClobberingMemoryAccess(Inst));
George Burgess IVe1100f52016-02-02 22:46:49 +00001184 }
1185 }
1186 }
1187
George Burgess IV5f308972016-07-19 01:29:15 +00001188 Walker->setAutoResetWalker(true);
1189 Walker->resetClobberWalker();
1190
George Burgess IVe1100f52016-02-02 22:46:49 +00001191 // Mark the uses in unreachable blocks as live on entry, so that they go
1192 // somewhere.
1193 for (auto &BB : F)
1194 if (!Visited.count(&BB))
1195 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001196}
George Burgess IVe1100f52016-02-02 22:46:49 +00001197
George Burgess IV5f308972016-07-19 01:29:15 +00001198MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1199
1200MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001201 if (Walker)
1202 return Walker.get();
1203
1204 Walker = make_unique<CachingWalker>(this, AA, DT);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001205 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001206}
1207
Daniel Berlin14300262016-06-21 18:39:20 +00001208MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1209 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
1210 AccessList *Accesses = getOrCreateAccessList(BB);
1211 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
1212 ValueToMemoryAccess.insert(std::make_pair(BB, Phi));
1213 // Phi's always are placed at the front of the block.
1214 Accesses->push_front(Phi);
1215 return Phi;
1216}
1217
1218MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
1219 MemoryAccess *Definition) {
1220 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1221 MemoryUseOrDef *NewAccess = createNewAccess(I);
1222 assert(
1223 NewAccess != nullptr &&
1224 "Tried to create a memory access for a non-memory touching instruction");
1225 NewAccess->setDefiningAccess(Definition);
1226 return NewAccess;
1227}
1228
1229MemoryAccess *MemorySSA::createMemoryAccessInBB(Instruction *I,
1230 MemoryAccess *Definition,
1231 const BasicBlock *BB,
1232 InsertionPlace Point) {
1233 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1234 auto *Accesses = getOrCreateAccessList(BB);
1235 if (Point == Beginning) {
1236 // It goes after any phi nodes
1237 auto AI = std::find_if(
1238 Accesses->begin(), Accesses->end(),
1239 [](const MemoryAccess &MA) { return !isa<MemoryPhi>(MA); });
1240
1241 Accesses->insert(AI, NewAccess);
1242 } else {
1243 Accesses->push_back(NewAccess);
1244 }
1245
1246 return NewAccess;
1247}
1248MemoryAccess *MemorySSA::createMemoryAccessBefore(Instruction *I,
1249 MemoryAccess *Definition,
1250 MemoryAccess *InsertPt) {
1251 assert(I->getParent() == InsertPt->getBlock() &&
1252 "New and old access must be in the same block");
1253 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1254 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
1255 Accesses->insert(AccessList::iterator(InsertPt), NewAccess);
1256 return NewAccess;
1257}
1258
1259MemoryAccess *MemorySSA::createMemoryAccessAfter(Instruction *I,
1260 MemoryAccess *Definition,
1261 MemoryAccess *InsertPt) {
1262 assert(I->getParent() == InsertPt->getBlock() &&
1263 "New and old access must be in the same block");
1264 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1265 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
1266 Accesses->insertAfter(AccessList::iterator(InsertPt), NewAccess);
1267 return NewAccess;
1268}
1269
George Burgess IVe1100f52016-02-02 22:46:49 +00001270/// \brief Helper function to create new memory accesses
Peter Collingbourneffecb142016-05-26 01:19:17 +00001271MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001272 // The assume intrinsic has a control dependency which we model by claiming
1273 // that it writes arbitrarily. Ignore that fake memory dependency here.
1274 // FIXME: Replace this special casing with a more accurate modelling of
1275 // assume's control dependency.
1276 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1277 if (II->getIntrinsicID() == Intrinsic::assume)
1278 return nullptr;
1279
George Burgess IVe1100f52016-02-02 22:46:49 +00001280 // Find out what affect this instruction has on memory.
1281 ModRefInfo ModRef = AA->getModRefInfo(I);
1282 bool Def = bool(ModRef & MRI_Mod);
1283 bool Use = bool(ModRef & MRI_Ref);
1284
1285 // It's possible for an instruction to not modify memory at all. During
1286 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +00001287 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +00001288 return nullptr;
1289
1290 assert((Def || Use) &&
1291 "Trying to create a memory access with a non-memory instruction");
1292
George Burgess IVb42b7622016-03-11 19:34:03 +00001293 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001294 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +00001295 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +00001296 else
George Burgess IVb42b7622016-03-11 19:34:03 +00001297 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
1298 ValueToMemoryAccess.insert(std::make_pair(I, MUD));
1299 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001300}
1301
1302MemoryAccess *MemorySSA::findDominatingDef(BasicBlock *UseBlock,
1303 enum InsertionPlace Where) {
1304 // Handle the initial case
1305 if (Where == Beginning)
1306 // The only thing that could define us at the beginning is a phi node
1307 if (MemoryPhi *Phi = getMemoryAccess(UseBlock))
1308 return Phi;
1309
1310 DomTreeNode *CurrNode = DT->getNode(UseBlock);
1311 // Need to be defined by our dominator
1312 if (Where == Beginning)
1313 CurrNode = CurrNode->getIDom();
1314 Where = End;
1315 while (CurrNode) {
1316 auto It = PerBlockAccesses.find(CurrNode->getBlock());
1317 if (It != PerBlockAccesses.end()) {
1318 auto &Accesses = It->second;
David Majnemerd7708772016-06-24 04:05:21 +00001319 for (MemoryAccess &RA : reverse(*Accesses)) {
1320 if (isa<MemoryDef>(RA) || isa<MemoryPhi>(RA))
1321 return &RA;
George Burgess IVe1100f52016-02-02 22:46:49 +00001322 }
1323 }
1324 CurrNode = CurrNode->getIDom();
1325 }
1326 return LiveOnEntryDef.get();
1327}
1328
1329/// \brief Returns true if \p Replacer dominates \p Replacee .
1330bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1331 const MemoryAccess *Replacee) const {
1332 if (isa<MemoryUseOrDef>(Replacee))
1333 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1334 const auto *MP = cast<MemoryPhi>(Replacee);
1335 // For a phi node, the use occurs in the predecessor block of the phi node.
1336 // Since we may occur multiple times in the phi node, we have to check each
1337 // operand to ensure Replacer dominates each operand where Replacee occurs.
1338 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +00001339 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +00001340 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1341 return false;
1342 }
1343 return true;
1344}
1345
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001346/// \brief If all arguments of a MemoryPHI are defined by the same incoming
1347/// argument, return that argument.
1348static MemoryAccess *onlySingleValue(MemoryPhi *MP) {
1349 MemoryAccess *MA = nullptr;
1350
1351 for (auto &Arg : MP->operands()) {
1352 if (!MA)
1353 MA = cast<MemoryAccess>(Arg);
1354 else if (MA != Arg)
1355 return nullptr;
1356 }
1357 return MA;
1358}
1359
1360/// \brief Properly remove \p MA from all of MemorySSA's lookup tables.
1361///
1362/// Because of the way the intrusive list and use lists work, it is important to
1363/// do removal in the right order.
1364void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1365 assert(MA->use_empty() &&
1366 "Trying to remove memory access that still has uses");
1367 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
1368 MUD->setDefiningAccess(nullptr);
1369 // Invalidate our walker's cache if necessary
1370 if (!isa<MemoryUse>(MA))
1371 Walker->invalidateInfo(MA);
1372 // The call below to erase will destroy MA, so we can't change the order we
1373 // are doing things here
1374 Value *MemoryInst;
1375 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1376 MemoryInst = MUD->getMemoryInst();
1377 } else {
1378 MemoryInst = MA->getBlock();
1379 }
1380 ValueToMemoryAccess.erase(MemoryInst);
1381
George Burgess IVe0e6e482016-03-02 02:35:04 +00001382 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
Daniel Berlinada263d2016-06-20 20:21:33 +00001383 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001384 Accesses->erase(MA);
George Burgess IVe0e6e482016-03-02 02:35:04 +00001385 if (Accesses->empty())
1386 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001387}
1388
1389void MemorySSA::removeMemoryAccess(MemoryAccess *MA) {
1390 assert(!isLiveOnEntryDef(MA) && "Trying to remove the live on entry def");
1391 // We can only delete phi nodes if they have no uses, or we can replace all
1392 // uses with a single definition.
1393 MemoryAccess *NewDefTarget = nullptr;
1394 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) {
1395 // Note that it is sufficient to know that all edges of the phi node have
1396 // the same argument. If they do, by the definition of dominance frontiers
1397 // (which we used to place this phi), that argument must dominate this phi,
1398 // and thus, must dominate the phi's uses, and so we will not hit the assert
1399 // below.
1400 NewDefTarget = onlySingleValue(MP);
1401 assert((NewDefTarget || MP->use_empty()) &&
1402 "We can't delete this memory phi");
1403 } else {
1404 NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
1405 }
1406
1407 // Re-point the uses at our defining access
1408 if (!MA->use_empty())
1409 MA->replaceAllUsesWith(NewDefTarget);
1410
1411 // The call below to erase will destroy MA, so we can't change the order we
1412 // are doing things here
1413 removeFromLookups(MA);
1414}
1415
George Burgess IVe1100f52016-02-02 22:46:49 +00001416void MemorySSA::print(raw_ostream &OS) const {
1417 MemorySSAAnnotatedWriter Writer(this);
1418 F.print(OS, &Writer);
1419}
1420
1421void MemorySSA::dump() const {
1422 MemorySSAAnnotatedWriter Writer(this);
1423 F.print(dbgs(), &Writer);
1424}
1425
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001426void MemorySSA::verifyMemorySSA() const {
1427 verifyDefUses(F);
1428 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001429 verifyOrdering(F);
1430}
1431
1432/// \brief Verify that the order and existence of MemoryAccesses matches the
1433/// order and existence of memory affecting instructions.
1434void MemorySSA::verifyOrdering(Function &F) const {
1435 // Walk all the blocks, comparing what the lookups think and what the access
1436 // lists think, as well as the order in the blocks vs the order in the access
1437 // lists.
1438 SmallVector<MemoryAccess *, 32> ActualAccesses;
1439 for (BasicBlock &B : F) {
1440 const AccessList *AL = getBlockAccesses(&B);
1441 MemoryAccess *Phi = getMemoryAccess(&B);
1442 if (Phi)
1443 ActualAccesses.push_back(Phi);
1444 for (Instruction &I : B) {
1445 MemoryAccess *MA = getMemoryAccess(&I);
1446 assert((!MA || AL) && "We have memory affecting instructions "
1447 "in this block but they are not in the "
1448 "access list");
1449 if (MA)
1450 ActualAccesses.push_back(MA);
1451 }
1452 // Either we hit the assert, really have no accesses, or we have both
1453 // accesses and an access list
1454 if (!AL)
1455 continue;
1456 assert(AL->size() == ActualAccesses.size() &&
1457 "We don't have the same number of accesses in the block as on the "
1458 "access list");
1459 auto ALI = AL->begin();
1460 auto AAI = ActualAccesses.begin();
1461 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1462 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1463 ++ALI;
1464 ++AAI;
1465 }
1466 ActualAccesses.clear();
1467 }
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001468}
1469
George Burgess IVe1100f52016-02-02 22:46:49 +00001470/// \brief Verify the domination properties of MemorySSA by checking that each
1471/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001472void MemorySSA::verifyDomination(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001473 for (BasicBlock &B : F) {
1474 // Phi nodes are attached to basic blocks
1475 if (MemoryPhi *MP = getMemoryAccess(&B)) {
1476 for (User *U : MP->users()) {
1477 BasicBlock *UseBlock;
1478 // Phi operands are used on edges, we simulate the right domination by
1479 // acting as if the use occurred at the end of the predecessor block.
1480 if (MemoryPhi *P = dyn_cast<MemoryPhi>(U)) {
1481 for (const auto &Arg : P->operands()) {
1482 if (Arg == MP) {
1483 UseBlock = P->getIncomingBlock(Arg);
1484 break;
1485 }
1486 }
1487 } else {
1488 UseBlock = cast<MemoryAccess>(U)->getBlock();
1489 }
George Burgess IV60adac42016-02-02 23:26:01 +00001490 (void)UseBlock;
George Burgess IVe1100f52016-02-02 22:46:49 +00001491 assert(DT->dominates(MP->getBlock(), UseBlock) &&
1492 "Memory PHI does not dominate it's uses");
1493 }
1494 }
1495
1496 for (Instruction &I : B) {
1497 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
1498 if (!MD)
1499 continue;
1500
Benjamin Kramer451f54c2016-02-22 13:11:58 +00001501 for (User *U : MD->users()) {
Daniel Berlinada263d2016-06-20 20:21:33 +00001502 BasicBlock *UseBlock;
1503 (void)UseBlock;
George Burgess IVe1100f52016-02-02 22:46:49 +00001504 // Things are allowed to flow to phi nodes over their predecessor edge.
1505 if (auto *P = dyn_cast<MemoryPhi>(U)) {
1506 for (const auto &Arg : P->operands()) {
1507 if (Arg == MD) {
1508 UseBlock = P->getIncomingBlock(Arg);
1509 break;
1510 }
1511 }
1512 } else {
1513 UseBlock = cast<MemoryAccess>(U)->getBlock();
1514 }
1515 assert(DT->dominates(MD->getBlock(), UseBlock) &&
1516 "Memory Def does not dominate it's uses");
1517 }
1518 }
1519 }
1520}
1521
1522/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
1523/// appears in the use list of \p Def.
1524///
1525/// llvm_unreachable is used instead of asserts because this may be called in
1526/// a build without asserts. In that case, we don't want this to turn into a
1527/// nop.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001528void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001529 // The live on entry use may cause us to get a NULL def here
1530 if (!Def) {
1531 if (!isLiveOnEntryDef(Use))
1532 llvm_unreachable("Null def but use not point to live on entry def");
1533 } else if (std::find(Def->user_begin(), Def->user_end(), Use) ==
1534 Def->user_end()) {
1535 llvm_unreachable("Did not find use in def's use list");
1536 }
1537}
1538
1539/// \brief Verify the immediate use information, by walking all the memory
1540/// accesses and verifying that, for each use, it appears in the
1541/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001542void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001543 for (BasicBlock &B : F) {
1544 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00001545 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00001546 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
1547 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00001548 "Incomplete MemoryPhi Node");
George Burgess IVe1100f52016-02-02 22:46:49 +00001549 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1550 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Daniel Berlin14300262016-06-21 18:39:20 +00001551 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001552
1553 for (Instruction &I : B) {
1554 if (MemoryAccess *MA = getMemoryAccess(&I)) {
1555 assert(isa<MemoryUseOrDef>(MA) &&
1556 "Found a phi node not attached to a bb");
1557 verifyUseInDefs(cast<MemoryUseOrDef>(MA)->getDefiningAccess(), MA);
1558 }
1559 }
1560 }
1561}
1562
1563MemoryAccess *MemorySSA::getMemoryAccess(const Value *I) const {
Daniel Berlinf6c9ae92016-02-10 17:41:25 +00001564 return ValueToMemoryAccess.lookup(I);
George Burgess IVe1100f52016-02-02 22:46:49 +00001565}
1566
1567MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
1568 return cast_or_null<MemoryPhi>(getMemoryAccess((const Value *)BB));
1569}
1570
1571/// \brief Determine, for two memory accesses in the same block,
1572/// whether \p Dominator dominates \p Dominatee.
1573/// \returns True if \p Dominator dominates \p Dominatee.
1574bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
1575 const MemoryAccess *Dominatee) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001576 assert((Dominator->getBlock() == Dominatee->getBlock()) &&
1577 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00001578
1579 // A node dominates itself.
1580 if (Dominatee == Dominator)
1581 return true;
1582
1583 // When Dominatee is defined on function entry, it is not dominated by another
1584 // memory access.
1585 if (isLiveOnEntryDef(Dominatee))
1586 return false;
1587
1588 // When Dominator is defined on function entry, it dominates the other memory
1589 // access.
1590 if (isLiveOnEntryDef(Dominator))
1591 return true;
1592
George Burgess IVe1100f52016-02-02 22:46:49 +00001593 // Get the access list for the block
Daniel Berlinada263d2016-06-20 20:21:33 +00001594 const AccessList *AccessList = getBlockAccesses(Dominator->getBlock());
1595 AccessList::const_reverse_iterator It(Dominator->getIterator());
George Burgess IVe1100f52016-02-02 22:46:49 +00001596
1597 // If we hit the beginning of the access list before we hit dominatee, we must
1598 // dominate it
1599 return std::none_of(It, AccessList->rend(),
1600 [&](const MemoryAccess &MA) { return &MA == Dominatee; });
1601}
1602
George Burgess IV5f308972016-07-19 01:29:15 +00001603bool MemorySSA::dominates(const MemoryAccess *Dominator,
1604 const MemoryAccess *Dominatee) const {
1605 if (Dominator == Dominatee)
1606 return true;
1607
1608 if (isLiveOnEntryDef(Dominatee))
1609 return false;
1610
1611 if (Dominator->getBlock() != Dominatee->getBlock())
1612 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
1613 return locallyDominates(Dominator, Dominatee);
1614}
1615
George Burgess IVe1100f52016-02-02 22:46:49 +00001616const static char LiveOnEntryStr[] = "liveOnEntry";
1617
1618void MemoryDef::print(raw_ostream &OS) const {
1619 MemoryAccess *UO = getDefiningAccess();
1620
1621 OS << getID() << " = MemoryDef(";
1622 if (UO && UO->getID())
1623 OS << UO->getID();
1624 else
1625 OS << LiveOnEntryStr;
1626 OS << ')';
1627}
1628
1629void MemoryPhi::print(raw_ostream &OS) const {
1630 bool First = true;
1631 OS << getID() << " = MemoryPhi(";
1632 for (const auto &Op : operands()) {
1633 BasicBlock *BB = getIncomingBlock(Op);
1634 MemoryAccess *MA = cast<MemoryAccess>(Op);
1635 if (!First)
1636 OS << ',';
1637 else
1638 First = false;
1639
1640 OS << '{';
1641 if (BB->hasName())
1642 OS << BB->getName();
1643 else
1644 BB->printAsOperand(OS, false);
1645 OS << ',';
1646 if (unsigned ID = MA->getID())
1647 OS << ID;
1648 else
1649 OS << LiveOnEntryStr;
1650 OS << '}';
1651 }
1652 OS << ')';
1653}
1654
1655MemoryAccess::~MemoryAccess() {}
1656
1657void MemoryUse::print(raw_ostream &OS) const {
1658 MemoryAccess *UO = getDefiningAccess();
1659 OS << "MemoryUse(";
1660 if (UO && UO->getID())
1661 OS << UO->getID();
1662 else
1663 OS << LiveOnEntryStr;
1664 OS << ')';
1665}
1666
1667void MemoryAccess::dump() const {
1668 print(dbgs());
1669 dbgs() << "\n";
1670}
1671
Chad Rosier232e29e2016-07-06 21:20:47 +00001672char MemorySSAPrinterLegacyPass::ID = 0;
1673
1674MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
1675 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
1676}
1677
1678void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
1679 AU.setPreservesAll();
1680 AU.addRequired<MemorySSAWrapperPass>();
1681 AU.addPreserved<MemorySSAWrapperPass>();
1682}
1683
1684bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
1685 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
1686 MSSA.print(dbgs());
1687 if (VerifyMemorySSA)
1688 MSSA.verifyMemorySSA();
1689 return false;
1690}
1691
Geoff Berryb96d3b22016-06-01 21:30:40 +00001692char MemorySSAAnalysis::PassID;
George Burgess IVe1100f52016-02-02 22:46:49 +00001693
Geoff Berryb96d3b22016-06-01 21:30:40 +00001694MemorySSA MemorySSAAnalysis::run(Function &F, AnalysisManager<Function> &AM) {
1695 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1696 auto &AA = AM.getResult<AAManager>(F);
1697 return MemorySSA(F, &AA, &DT);
George Burgess IVe1100f52016-02-02 22:46:49 +00001698}
1699
Geoff Berryb96d3b22016-06-01 21:30:40 +00001700PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
1701 FunctionAnalysisManager &AM) {
1702 OS << "MemorySSA for function: " << F.getName() << "\n";
1703 AM.getResult<MemorySSAAnalysis>(F).print(OS);
1704
1705 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00001706}
1707
Geoff Berryb96d3b22016-06-01 21:30:40 +00001708PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
1709 FunctionAnalysisManager &AM) {
1710 AM.getResult<MemorySSAAnalysis>(F).verifyMemorySSA();
1711
1712 return PreservedAnalyses::all();
1713}
1714
1715char MemorySSAWrapperPass::ID = 0;
1716
1717MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
1718 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
1719}
1720
1721void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
1722
1723void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001724 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001725 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
1726 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001727}
1728
Geoff Berryb96d3b22016-06-01 21:30:40 +00001729bool MemorySSAWrapperPass::runOnFunction(Function &F) {
1730 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1731 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1732 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00001733 return false;
1734}
1735
Geoff Berryb96d3b22016-06-01 21:30:40 +00001736void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00001737
Geoff Berryb96d3b22016-06-01 21:30:40 +00001738void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001739 MSSA->print(OS);
1740}
1741
George Burgess IVe1100f52016-02-02 22:46:49 +00001742MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
1743
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001744MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A,
1745 DominatorTree *D)
George Burgess IV5f308972016-07-19 01:29:15 +00001746 : MemorySSAWalker(M), Walker(*M, *A, *D, Cache),
1747 AutoResetWalker(true) {}
George Burgess IVe1100f52016-02-02 22:46:49 +00001748
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001749MemorySSA::CachingWalker::~CachingWalker() {}
George Burgess IVe1100f52016-02-02 22:46:49 +00001750
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001751void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) {
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001752 // TODO: We can do much better cache invalidation with differently stored
1753 // caches. For now, for MemoryUses, we simply remove them
1754 // from the cache, and kill the entire call/non-call cache for everything
1755 // else. The problem is for phis or defs, currently we'd need to follow use
1756 // chains down and invalidate anything below us in the chain that currently
1757 // terminates at this access.
1758
1759 // See if this is a MemoryUse, if so, just remove the cached info. MemoryUse
1760 // is by definition never a barrier, so nothing in the cache could point to
1761 // this use. In that case, we only need invalidate the info for the use
1762 // itself.
1763
1764 if (MemoryUse *MU = dyn_cast<MemoryUse>(MA)) {
George Burgess IV5f308972016-07-19 01:29:15 +00001765 UpwardsMemoryQuery Q(MU->getMemoryInst(), MU);
1766 Cache.remove(MU, Q.StartingLoc, Q.IsCall);
Geoff Berry9fe26e62016-04-22 14:44:10 +00001767 } else {
1768 // 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 +00001769 Cache.clear();
Geoff Berry9fe26e62016-04-22 14:44:10 +00001770 }
1771
Filipe Cabecinhas0da99372016-04-29 15:22:48 +00001772#ifdef EXPENSIVE_CHECKS
Geoff Berry9fe26e62016-04-22 14:44:10 +00001773 verifyRemoved(MA);
1774#endif
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001775}
1776
George Burgess IVe1100f52016-02-02 22:46:49 +00001777/// \brief Walk the use-def chains starting at \p MA and find
1778/// the MemoryAccess that actually clobbers Loc.
1779///
1780/// \returns our clobbering memory access
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001781MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
1782 MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +00001783 MemoryAccess *New = Walker.findClobber(StartingAccess, Q);
1784#ifdef EXPENSIVE_CHECKS
1785 MemoryAccess *NewNoCache =
1786 Walker.findClobber(StartingAccess, Q, /*UseWalkerCache=*/false);
1787 assert(NewNoCache == New && "Cache made us hand back a different result?");
1788#endif
1789 if (AutoResetWalker)
1790 resetClobberWalker();
1791 return New;
George Burgess IVe1100f52016-02-02 22:46:49 +00001792}
1793
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001794MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
1795 MemoryAccess *StartingAccess, MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001796 if (isa<MemoryPhi>(StartingAccess))
1797 return StartingAccess;
1798
1799 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
1800 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
1801 return StartingUseOrDef;
1802
1803 Instruction *I = StartingUseOrDef->getMemoryInst();
1804
1805 // Conservatively, fences are always clobbers, so don't perform the walk if we
1806 // hit a fence.
David Majnemera940f362016-07-15 17:19:24 +00001807 if (!ImmutableCallSite(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00001808 return StartingUseOrDef;
1809
1810 UpwardsMemoryQuery Q;
1811 Q.OriginalAccess = StartingUseOrDef;
1812 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00001813 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00001814 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00001815
George Burgess IV5f308972016-07-19 01:29:15 +00001816 if (auto *CacheResult = Cache.lookup(StartingUseOrDef, Loc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00001817 return CacheResult;
1818
1819 // Unlike the other function, do not walk to the def of a def, because we are
1820 // handed something we already believe is the clobbering access.
1821 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
1822 ? StartingUseOrDef->getDefiningAccess()
1823 : StartingUseOrDef;
1824
1825 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00001826 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
1827 DEBUG(dbgs() << *StartingUseOrDef << "\n");
1828 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
1829 DEBUG(dbgs() << *Clobber << "\n");
1830 return Clobber;
1831}
1832
1833MemoryAccess *
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001834MemorySSA::CachingWalker::getClobberingMemoryAccess(const Instruction *I) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001835 // There should be no way to lookup an instruction and get a phi as the
1836 // access, since we only map BB's to PHI's. So, this must be a use or def.
1837 auto *StartingAccess = cast<MemoryUseOrDef>(MSSA->getMemoryAccess(I));
1838
George Burgess IV5f308972016-07-19 01:29:15 +00001839 UpwardsMemoryQuery Q(I, StartingAccess);
David Majnemera940f362016-07-15 17:19:24 +00001840 // We can't sanely do anything with a fences, they conservatively
George Burgess IVe1100f52016-02-02 22:46:49 +00001841 // clobber all memory, and have no locations to get pointers from to
David Majnemera940f362016-07-15 17:19:24 +00001842 // try to disambiguate.
George Burgess IV5f308972016-07-19 01:29:15 +00001843 if (!Q.IsCall && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00001844 return StartingAccess;
1845
George Burgess IV5f308972016-07-19 01:29:15 +00001846 if (auto *CacheResult = Cache.lookup(StartingAccess, Q.StartingLoc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00001847 return CacheResult;
1848
1849 // Start with the thing we already think clobbers this location
1850 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
1851
1852 // At this point, DefiningAccess may be the live on entry def.
1853 // If it is, we will not get a better result.
1854 if (MSSA->isLiveOnEntryDef(DefiningAccess))
1855 return DefiningAccess;
1856
1857 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00001858 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
1859 DEBUG(dbgs() << *DefiningAccess << "\n");
1860 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
1861 DEBUG(dbgs() << *Result << "\n");
1862
1863 return Result;
1864}
1865
Geoff Berry9fe26e62016-04-22 14:44:10 +00001866// Verify that MA doesn't exist in any of the caches.
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001867void MemorySSA::CachingWalker::verifyRemoved(MemoryAccess *MA) {
George Burgess IV5f308972016-07-19 01:29:15 +00001868 assert(!Cache.contains(MA) && "Found removed MemoryAccess in cache.");
Geoff Berry9fe26e62016-04-22 14:44:10 +00001869}
1870
George Burgess IVe1100f52016-02-02 22:46:49 +00001871MemoryAccess *
1872DoNothingMemorySSAWalker::getClobberingMemoryAccess(const Instruction *I) {
1873 MemoryAccess *MA = MSSA->getMemoryAccess(I);
1874 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
1875 return Use->getDefiningAccess();
1876 return MA;
1877}
1878
1879MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
1880 MemoryAccess *StartingAccess, MemoryLocation &) {
1881 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
1882 return Use->getDefiningAccess();
1883 return StartingAccess;
1884}
George Burgess IV5f308972016-07-19 01:29:15 +00001885} // namespace llvm