blob: 13ddd835c4d1bbeac2027319ced4bd7eeb571895 [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
George Burgess IV5f308972016-07-19 01:29:15 +0000239 bool FoundClobber = false;
240 DenseSet<MemoryAccessPair> VisitedPhis;
241 SmallVector<MemoryAccessPair, 8> Worklist;
242 Worklist.emplace_back(Start, StartLoc);
243 // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
244 // is found, complain.
245 while (!Worklist.empty()) {
246 MemoryAccessPair MAP = Worklist.pop_back_val();
247 // All we care about is that nothing from Start to ClobberAt clobbers Start.
248 // We learn nothing from revisiting nodes.
249 if (!VisitedPhis.insert(MAP).second)
250 continue;
251
252 for (MemoryAccess *MA : def_chain(MAP.first)) {
253 if (MA == ClobberAt) {
254 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
255 // instructionClobbersQuery isn't essentially free, so don't use `|=`,
256 // since it won't let us short-circuit.
257 //
258 // Also, note that this can't be hoisted out of the `Worklist` loop,
259 // since MD may only act as a clobber for 1 of N MemoryLocations.
260 FoundClobber = FoundClobber || MSSA.isLiveOnEntryDef(MD) ||
261 instructionClobbersQuery(MD, MAP.second, Query, AA);
262 }
263 break;
264 }
265
266 // We should never hit liveOnEntry, unless it's the clobber.
267 assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
268
269 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
270 (void)MD;
271 assert(!instructionClobbersQuery(MD, MAP.second, Query, AA) &&
272 "Found clobber before reaching ClobberAt!");
273 continue;
274 }
275
276 assert(isa<MemoryPhi>(MA));
277 Worklist.append(upward_defs_begin({MA, MAP.second}), upward_defs_end());
278 }
279 }
280
281 // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
282 // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
283 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
284 "ClobberAt never acted as a clobber");
285}
286
287/// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
288/// in one class.
289class ClobberWalker {
290 /// Save a few bytes by using unsigned instead of size_t.
291 using ListIndex = unsigned;
292
293 /// Represents a span of contiguous MemoryDefs, potentially ending in a
294 /// MemoryPhi.
295 struct DefPath {
296 MemoryLocation Loc;
297 // Note that, because we always walk in reverse, Last will always dominate
298 // First. Also note that First and Last are inclusive.
299 MemoryAccess *First;
300 MemoryAccess *Last;
301 // N.B. Blocker is currently basically unused. The goal is to use it to make
302 // cache invalidation better, but we're not there yet.
303 MemoryAccess *Blocker;
304 Optional<ListIndex> Previous;
305
306 DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
307 Optional<ListIndex> Previous)
308 : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
309
310 DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
311 Optional<ListIndex> Previous)
312 : DefPath(Loc, Init, Init, Previous) {}
313 };
314
315 const MemorySSA &MSSA;
316 AliasAnalysis &AA;
317 DominatorTree &DT;
318 WalkerCache &WC;
319 UpwardsMemoryQuery *Query;
320 bool UseCache;
321
322 // Phi optimization bookkeeping
323 SmallVector<DefPath, 32> Paths;
324 DenseSet<ConstMemoryAccessPair> VisitedPhis;
325 DenseMap<const BasicBlock *, MemoryAccess *> WalkTargetCache;
326
327 void setUseCache(bool Use) { UseCache = Use; }
328 bool shouldIgnoreCache() const {
329 // UseCache will only be false when we're debugging, or when expensive
330 // checks are enabled. In either case, we don't care deeply about speed.
331 return LLVM_UNLIKELY(!UseCache);
332 }
333
334 void addCacheEntry(const MemoryAccess *What, MemoryAccess *To,
335 const MemoryLocation &Loc) const {
Daniel Berlin5c46b942016-07-19 22:49:43 +0000336// EXPENSIVE_CHECKS because most of these queries are redundant.
George Burgess IV5f308972016-07-19 01:29:15 +0000337#ifdef EXPENSIVE_CHECKS
338 assert(MSSA.dominates(To, What));
339#endif
340 if (shouldIgnoreCache())
341 return;
342 WC.insert(What, To, Loc, Query->IsCall);
343 }
344
345 MemoryAccess *lookupCache(const MemoryAccess *MA, const MemoryLocation &Loc) {
346 return shouldIgnoreCache() ? nullptr : WC.lookup(MA, Loc, Query->IsCall);
347 }
348
349 void cacheDefPath(const DefPath &DN, MemoryAccess *Target) const {
350 if (shouldIgnoreCache())
351 return;
352
353 for (MemoryAccess *MA : def_chain(DN.First, DN.Last))
354 addCacheEntry(MA, Target, DN.Loc);
355
356 // DefPaths only express the path we walked. So, DN.Last could either be a
357 // thing we want to cache, or not.
358 if (DN.Last != Target)
359 addCacheEntry(DN.Last, Target, DN.Loc);
360 }
361
362 /// Find the nearest def or phi that `From` can legally be optimized to.
363 ///
364 /// FIXME: Deduplicate this with MSSA::findDominatingDef. Ideally, MSSA should
365 /// keep track of this information for us, and allow us O(1) lookups of this
366 /// info.
367 MemoryAccess *getWalkTarget(const MemoryPhi *From) {
George Burgess IV5f308972016-07-19 01:29:15 +0000368 assert(From->getNumOperands() && "Phi with no operands?");
369
370 BasicBlock *BB = From->getBlock();
371 auto At = WalkTargetCache.find(BB);
372 if (At != WalkTargetCache.end())
373 return At->second;
374
375 SmallVector<const BasicBlock *, 8> ToCache;
376 ToCache.push_back(BB);
377
378 MemoryAccess *Result = MSSA.getLiveOnEntryDef();
379 DomTreeNode *Node = DT.getNode(BB);
380 while ((Node = Node->getIDom())) {
381 auto At = WalkTargetCache.find(BB);
382 if (At != WalkTargetCache.end()) {
383 Result = At->second;
384 break;
385 }
386
387 auto *Accesses = MSSA.getBlockAccesses(Node->getBlock());
388 if (Accesses) {
389 auto Iter = find_if(reverse(*Accesses), [](const MemoryAccess &MA) {
390 return !isa<MemoryUse>(MA);
391 });
392 if (Iter != Accesses->rend()) {
393 Result = const_cast<MemoryAccess *>(&*Iter);
394 break;
395 }
396 }
397
398 ToCache.push_back(Node->getBlock());
399 }
400
401 for (const BasicBlock *BB : ToCache)
402 WalkTargetCache.insert({BB, Result});
403 return Result;
404 }
405
406 /// Result of calling walkToPhiOrClobber.
407 struct UpwardsWalkResult {
408 /// The "Result" of the walk. Either a clobber, the last thing we walked, or
409 /// both.
410 MemoryAccess *Result;
411 bool IsKnownClobber;
412 bool FromCache;
413 };
414
415 /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
416 /// This will update Desc.Last as it walks. It will (optionally) also stop at
417 /// StopAt.
418 ///
419 /// This does not test for whether StopAt is a clobber
420 UpwardsWalkResult walkToPhiOrClobber(DefPath &Desc,
421 MemoryAccess *StopAt = nullptr) {
422 assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
423
424 for (MemoryAccess *Current : def_chain(Desc.Last)) {
425 Desc.Last = Current;
426 if (Current == StopAt)
427 return {Current, false, false};
428
429 if (auto *MD = dyn_cast<MemoryDef>(Current))
430 if (MSSA.isLiveOnEntryDef(MD) ||
431 instructionClobbersQuery(MD, Desc.Loc, *Query, AA))
432 return {MD, true, false};
433
434 // Cache checks must be done last, because if Current is a clobber, the
435 // cache will contain the clobber for Current.
436 if (MemoryAccess *MA = lookupCache(Current, Desc.Loc))
437 return {MA, true, true};
438 }
439
440 assert(isa<MemoryPhi>(Desc.Last) &&
441 "Ended at a non-clobber that's not a phi?");
442 return {Desc.Last, false, false};
443 }
444
445 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
446 ListIndex PriorNode) {
447 auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),
448 upward_defs_end());
449 for (const MemoryAccessPair &P : UpwardDefs) {
450 PausedSearches.push_back(Paths.size());
451 Paths.emplace_back(P.second, P.first, PriorNode);
452 }
453 }
454
455 /// Represents a search that terminated after finding a clobber. This clobber
456 /// may or may not be present in the path of defs from LastNode..SearchStart,
457 /// since it may have been retrieved from cache.
458 struct TerminatedPath {
459 MemoryAccess *Clobber;
460 ListIndex LastNode;
461 };
462
463 /// Get an access that keeps us from optimizing to the given phi.
464 ///
465 /// PausedSearches is an array of indices into the Paths array. Its incoming
466 /// value is the indices of searches that stopped at the last phi optimization
467 /// target. It's left in an unspecified state.
468 ///
469 /// If this returns None, NewPaused is a vector of searches that terminated
470 /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
471 Optional<ListIndex>
472 getBlockingAccess(MemoryAccess *StopWhere,
473 SmallVectorImpl<ListIndex> &PausedSearches,
474 SmallVectorImpl<ListIndex> &NewPaused,
475 SmallVectorImpl<TerminatedPath> &Terminated) {
476 assert(!PausedSearches.empty() && "No searches to continue?");
477
478 // BFS vs DFS really doesn't make a difference here, so just do a DFS with
479 // PausedSearches as our stack.
480 while (!PausedSearches.empty()) {
481 ListIndex PathIndex = PausedSearches.pop_back_val();
482 DefPath &Node = Paths[PathIndex];
483
484 // If we've already visited this path with this MemoryLocation, we don't
485 // need to do so again.
486 //
487 // NOTE: That we just drop these paths on the ground makes caching
488 // behavior sporadic. e.g. given a diamond:
489 // A
490 // B C
491 // D
492 //
493 // ...If we walk D, B, A, C, we'll only cache the result of phi
494 // optimization for A, B, and D; C will be skipped because it dies here.
495 // This arguably isn't the worst thing ever, since:
496 // - We generally query things in a top-down order, so if we got below D
497 // without needing cache entries for {C, MemLoc}, then chances are
498 // that those cache entries would end up ultimately unused.
499 // - We still cache things for A, so C only needs to walk up a bit.
500 // If this behavior becomes problematic, we can fix without a ton of extra
501 // work.
502 if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
503 continue;
504
505 UpwardsWalkResult Res = walkToPhiOrClobber(Node, /*StopAt=*/StopWhere);
506 if (Res.IsKnownClobber) {
507 assert(Res.Result != StopWhere || Res.FromCache);
508 // If this wasn't a cache hit, we hit a clobber when walking. That's a
509 // failure.
510 if (!Res.FromCache || !MSSA.dominates(Res.Result, StopWhere))
511 return PathIndex;
512
513 // Otherwise, it's a valid thing to potentially optimize to.
514 Terminated.push_back({Res.Result, PathIndex});
515 continue;
516 }
517
518 if (Res.Result == StopWhere) {
519 // We've hit our target. Save this path off for if we want to continue
520 // walking.
521 NewPaused.push_back(PathIndex);
522 continue;
523 }
524
525 assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
526 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
527 }
528
529 return None;
530 }
531
532 template <typename T, typename Walker>
533 struct generic_def_path_iterator
534 : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
535 std::forward_iterator_tag, T *> {
536 generic_def_path_iterator() : W(nullptr), N(None) {}
537 generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
538
539 T &operator*() const { return curNode(); }
540
541 generic_def_path_iterator &operator++() {
542 N = curNode().Previous;
543 return *this;
544 }
545
546 bool operator==(const generic_def_path_iterator &O) const {
547 if (N.hasValue() != O.N.hasValue())
548 return false;
549 return !N.hasValue() || *N == *O.N;
550 }
551
552 private:
553 T &curNode() const { return W->Paths[*N]; }
554
555 Walker *W;
556 Optional<ListIndex> N;
557 };
558
559 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
560 using const_def_path_iterator =
561 generic_def_path_iterator<const DefPath, const ClobberWalker>;
562
563 iterator_range<def_path_iterator> def_path(ListIndex From) {
564 return make_range(def_path_iterator(this, From), def_path_iterator());
565 }
566
567 iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
568 return make_range(const_def_path_iterator(this, From),
569 const_def_path_iterator());
570 }
571
572 struct OptznResult {
573 /// The path that contains our result.
574 TerminatedPath PrimaryClobber;
575 /// The paths that we can legally cache back from, but that aren't
576 /// necessarily the result of the Phi optimization.
577 SmallVector<TerminatedPath, 4> OtherClobbers;
578 };
579
580 ListIndex defPathIndex(const DefPath &N) const {
581 // The assert looks nicer if we don't need to do &N
582 const DefPath *NP = &N;
583 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
584 "Out of bounds DefPath!");
585 return NP - &Paths.front();
586 }
587
588 /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
589 /// that act as legal clobbers. Note that this won't return *all* clobbers.
590 ///
591 /// Phi optimization algorithm tl;dr:
592 /// - Find the earliest def/phi, A, we can optimize to
593 /// - Find if all paths from the starting memory access ultimately reach A
594 /// - If not, optimization isn't possible.
595 /// - Otherwise, walk from A to another clobber or phi, A'.
596 /// - If A' is a def, we're done.
597 /// - If A' is a phi, try to optimize it.
598 ///
599 /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
600 /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
601 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
602 const MemoryLocation &Loc) {
603 assert(Paths.empty() && VisitedPhis.empty() &&
604 "Reset the optimization state.");
605
606 Paths.emplace_back(Loc, Start, Phi, None);
607 // Stores how many "valid" optimization nodes we had prior to calling
608 // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
609 auto PriorPathsSize = Paths.size();
610
611 SmallVector<ListIndex, 16> PausedSearches;
612 SmallVector<ListIndex, 8> NewPaused;
613 SmallVector<TerminatedPath, 4> TerminatedPaths;
614
615 addSearches(Phi, PausedSearches, 0);
616
617 // Moves the TerminatedPath with the "most dominated" Clobber to the end of
618 // Paths.
619 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
620 assert(!Paths.empty() && "Need a path to move");
George Burgess IV5f308972016-07-19 01:29:15 +0000621 auto Dom = Paths.begin();
622 for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
623 if (!MSSA.dominates(I->Clobber, Dom->Clobber))
624 Dom = I;
625 auto Last = Paths.end() - 1;
626 if (Last != Dom)
627 std::iter_swap(Last, Dom);
628 };
629
630 MemoryPhi *Current = Phi;
631 while (1) {
632 assert(!MSSA.isLiveOnEntryDef(Current) &&
633 "liveOnEntry wasn't treated as a clobber?");
634
635 MemoryAccess *Target = getWalkTarget(Current);
636 // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
637 // optimization for the prior phi.
638 assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
639 return MSSA.dominates(P.Clobber, Target);
640 }));
641
642 // FIXME: This is broken, because the Blocker may be reported to be
643 // liveOnEntry, and we'll happily wait for that to disappear (read: never)
644 // For the moment, this is fine, since we do basically nothing with
645 // blocker info.
646 if (Optional<ListIndex> Blocker = getBlockingAccess(
647 Target, PausedSearches, NewPaused, TerminatedPaths)) {
648 MemoryAccess *BlockingAccess = Paths[*Blocker].Last;
649 // Cache our work on the blocking node, since we know that's correct.
650 cacheDefPath(Paths[*Blocker], BlockingAccess);
651
652 // Find the node we started at. We can't search based on N->Last, since
653 // we may have gone around a loop with a different MemoryLocation.
654 auto Iter = find_if(def_path(*Blocker), [&](const DefPath &N) {
655 return defPathIndex(N) < PriorPathsSize;
656 });
657 assert(Iter != def_path_iterator());
658
659 DefPath &CurNode = *Iter;
660 assert(CurNode.Last == Current);
661 CurNode.Blocker = BlockingAccess;
662
663 // Two things:
664 // A. We can't reliably cache all of NewPaused back. Consider a case
665 // where we have two paths in NewPaused; one of which can't optimize
666 // above this phi, whereas the other can. If we cache the second path
667 // back, we'll end up with suboptimal cache entries. We can handle
668 // cases like this a bit better when we either try to find all
669 // clobbers that block phi optimization, or when our cache starts
670 // supporting unfinished searches.
671 // B. We can't reliably cache TerminatedPaths back here without doing
672 // extra checks; consider a case like:
673 // T
674 // / \
675 // D C
676 // \ /
677 // S
678 // Where T is our target, C is a node with a clobber on it, D is a
679 // diamond (with a clobber *only* on the left or right node, N), and
680 // S is our start. Say we walk to D, through the node opposite N
681 // (read: ignoring the clobber), and see a cache entry in the top
682 // node of D. That cache entry gets put into TerminatedPaths. We then
683 // walk up to C (N is later in our worklist), find the clobber, and
684 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
685 // the bottom part of D to the cached clobber, ignoring the clobber
686 // in N. Again, this problem goes away if we start tracking all
687 // blockers for a given phi optimization.
688 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
689 return {Result, {}};
690 }
691
692 // If there's nothing left to search, then all paths led to valid clobbers
693 // that we got from our cache; pick the nearest to the start, and allow
694 // the rest to be cached back.
695 if (NewPaused.empty()) {
696 MoveDominatedPathToEnd(TerminatedPaths);
697 TerminatedPath Result = TerminatedPaths.pop_back_val();
698 return {Result, std::move(TerminatedPaths)};
699 }
700
701 MemoryAccess *DefChainEnd = nullptr;
702 SmallVector<TerminatedPath, 4> Clobbers;
703 for (ListIndex Paused : NewPaused) {
704 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
705 if (WR.IsKnownClobber)
706 Clobbers.push_back({WR.Result, Paused});
707 else
708 // Micro-opt: If we hit the end of the chain, save it.
709 DefChainEnd = WR.Result;
710 }
711
712 if (!TerminatedPaths.empty()) {
713 // If we couldn't find the dominating phi/liveOnEntry in the above loop,
714 // do it now.
715 if (!DefChainEnd)
716 for (MemoryAccess *MA : def_chain(Target))
717 DefChainEnd = MA;
718
719 // If any of the terminated paths don't dominate the phi we'll try to
720 // optimize, we need to figure out what they are and quit.
721 const BasicBlock *ChainBB = DefChainEnd->getBlock();
722 for (const TerminatedPath &TP : TerminatedPaths) {
723 // Because we know that DefChainEnd is as "high" as we can go, we
724 // don't need local dominance checks; BB dominance is sufficient.
725 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
726 Clobbers.push_back(TP);
727 }
728 }
729
730 // If we have clobbers in the def chain, find the one closest to Current
731 // and quit.
732 if (!Clobbers.empty()) {
733 MoveDominatedPathToEnd(Clobbers);
734 TerminatedPath Result = Clobbers.pop_back_val();
735 return {Result, std::move(Clobbers)};
736 }
737
738 assert(all_of(NewPaused,
739 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
740
741 // Because liveOnEntry is a clobber, this must be a phi.
742 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
743
744 PriorPathsSize = Paths.size();
745 PausedSearches.clear();
746 for (ListIndex I : NewPaused)
747 addSearches(DefChainPhi, PausedSearches, I);
748 NewPaused.clear();
749
750 Current = DefChainPhi;
751 }
752 }
753
754 /// Caches everything in an OptznResult.
755 void cacheOptResult(const OptznResult &R) {
756 if (R.OtherClobbers.empty()) {
757 // If we're not going to be caching OtherClobbers, don't bother with
758 // marking visited/etc.
759 for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode))
760 cacheDefPath(N, R.PrimaryClobber.Clobber);
761 return;
762 }
763
764 // PrimaryClobber is our answer. If we can cache anything back, we need to
765 // stop caching when we visit PrimaryClobber.
766 SmallBitVector Visited(Paths.size());
767 for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode)) {
768 Visited[defPathIndex(N)] = true;
769 cacheDefPath(N, R.PrimaryClobber.Clobber);
770 }
771
772 for (const TerminatedPath &P : R.OtherClobbers) {
773 for (const DefPath &N : const_def_path(P.LastNode)) {
774 ListIndex NIndex = defPathIndex(N);
775 if (Visited[NIndex])
776 break;
777 Visited[NIndex] = true;
778 cacheDefPath(N, P.Clobber);
779 }
780 }
781 }
782
783 void verifyOptResult(const OptznResult &R) const {
784 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
785 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
786 }));
787 }
788
789 void resetPhiOptznState() {
790 Paths.clear();
791 VisitedPhis.clear();
792 }
793
794public:
795 ClobberWalker(const MemorySSA &MSSA, AliasAnalysis &AA, DominatorTree &DT,
796 WalkerCache &WC)
797 : MSSA(MSSA), AA(AA), DT(DT), WC(WC), UseCache(true) {}
798
799 void reset() { WalkTargetCache.clear(); }
800
801 /// Finds the nearest clobber for the given query, optimizing phis if
802 /// possible.
803 MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q,
804 bool UseWalkerCache = true) {
805 setUseCache(UseWalkerCache);
806 Query = &Q;
807
808 MemoryAccess *Current = Start;
809 // This walker pretends uses don't exist. If we're handed one, silently grab
810 // its def. (This has the nice side-effect of ensuring we never cache uses)
811 if (auto *MU = dyn_cast<MemoryUse>(Start))
812 Current = MU->getDefiningAccess();
813
814 DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
815 // Fast path for the overly-common case (no crazy phi optimization
816 // necessary)
817 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000818 MemoryAccess *Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000819 if (WalkResult.IsKnownClobber) {
820 cacheDefPath(FirstDesc, WalkResult.Result);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000821 Result = WalkResult.Result;
822 } else {
823 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
824 Current, Q.StartingLoc);
825 verifyOptResult(OptRes);
826 cacheOptResult(OptRes);
827 resetPhiOptznState();
828 Result = OptRes.PrimaryClobber.Clobber;
George Burgess IV5f308972016-07-19 01:29:15 +0000829 }
830
George Burgess IV5f308972016-07-19 01:29:15 +0000831#ifdef EXPENSIVE_CHECKS
George Burgess IV93ea19b2016-07-24 07:03:49 +0000832 checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000833#endif
George Burgess IV93ea19b2016-07-24 07:03:49 +0000834 return Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000835 }
836};
837
838struct RenamePassData {
839 DomTreeNode *DTN;
840 DomTreeNode::const_iterator ChildIt;
841 MemoryAccess *IncomingVal;
842
843 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
844 MemoryAccess *M)
845 : DTN(D), ChildIt(It), IncomingVal(M) {}
846 void swap(RenamePassData &RHS) {
847 std::swap(DTN, RHS.DTN);
848 std::swap(ChildIt, RHS.ChildIt);
849 std::swap(IncomingVal, RHS.IncomingVal);
850 }
851};
852} // anonymous namespace
853
854namespace llvm {
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000855/// \brief A MemorySSAWalker that does AA walks and caching of lookups to
856/// disambiguate accesses.
857///
858/// FIXME: The current implementation of this can take quadratic space in rare
859/// cases. This can be fixed, but it is something to note until it is fixed.
860///
861/// In order to trigger this behavior, you need to store to N distinct locations
862/// (that AA can prove don't alias), perform M stores to other memory
863/// locations that AA can prove don't alias any of the initial N locations, and
864/// then load from all of the N locations. In this case, we insert M cache
865/// entries for each of the N loads.
866///
867/// For example:
868/// define i32 @foo() {
869/// %a = alloca i32, align 4
870/// %b = alloca i32, align 4
871/// store i32 0, i32* %a, align 4
872/// store i32 0, i32* %b, align 4
873///
874/// ; Insert M stores to other memory that doesn't alias %a or %b here
875///
876/// %c = load i32, i32* %a, align 4 ; Caches M entries in
877/// ; CachedUpwardsClobberingAccess for the
878/// ; MemoryLocation %a
879/// %d = load i32, i32* %b, align 4 ; Caches M entries in
880/// ; CachedUpwardsClobberingAccess for the
881/// ; MemoryLocation %b
882///
883/// ; For completeness' sake, loading %a or %b again would not cache *another*
884/// ; M entries.
885/// %r = add i32 %c, %d
886/// ret i32 %r
887/// }
888class MemorySSA::CachingWalker final : public MemorySSAWalker {
George Burgess IV5f308972016-07-19 01:29:15 +0000889 WalkerCache Cache;
890 ClobberWalker Walker;
891 bool AutoResetWalker;
892
893 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, UpwardsMemoryQuery &);
894 void verifyRemoved(MemoryAccess *);
895
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000896public:
897 CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *);
898 ~CachingWalker() override;
899
George Burgess IV400ae402016-07-20 19:51:34 +0000900 using MemorySSAWalker::getClobberingMemoryAccess;
901 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override;
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000902 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
903 MemoryLocation &) override;
904 void invalidateInfo(MemoryAccess *) override;
905
George Burgess IV5f308972016-07-19 01:29:15 +0000906 /// Whether we call resetClobberWalker() after each time we *actually* walk to
907 /// answer a clobber query.
908 void setAutoResetWalker(bool AutoReset) { AutoResetWalker = AutoReset; }
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000909
George Burgess IV5f308972016-07-19 01:29:15 +0000910 /// Drop the walker's persistent data structures. At the moment, this means
911 /// "drop the walker's cache of BasicBlocks ->
912 /// earliest-MemoryAccess-we-can-optimize-to". This is necessary if we're
913 /// going to have DT updates, if we remove MemoryAccesses, etc.
914 void resetClobberWalker() { Walker.reset(); }
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000915};
George Burgess IVe1100f52016-02-02 22:46:49 +0000916
George Burgess IVe1100f52016-02-02 22:46:49 +0000917/// \brief Rename a single basic block into MemorySSA form.
918/// Uses the standard SSA renaming algorithm.
919/// \returns The new incoming value.
920MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB,
921 MemoryAccess *IncomingVal) {
922 auto It = PerBlockAccesses.find(BB);
923 // Skip most processing if the list is empty.
924 if (It != PerBlockAccesses.end()) {
Daniel Berlinada263d2016-06-20 20:21:33 +0000925 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000926 for (MemoryAccess &L : *Accesses) {
927 switch (L.getValueID()) {
928 case Value::MemoryUseVal:
929 cast<MemoryUse>(&L)->setDefiningAccess(IncomingVal);
930 break;
931 case Value::MemoryDefVal:
932 // We can't legally optimize defs, because we only allow single
933 // memory phis/uses on operations, and if we optimize these, we can
934 // end up with multiple reaching defs. Uses do not have this
935 // problem, since they do not produce a value
936 cast<MemoryDef>(&L)->setDefiningAccess(IncomingVal);
937 IncomingVal = &L;
938 break;
939 case Value::MemoryPhiVal:
940 IncomingVal = &L;
941 break;
942 }
943 }
944 }
945
946 // Pass through values to our successors
947 for (const BasicBlock *S : successors(BB)) {
948 auto It = PerBlockAccesses.find(S);
949 // Rename the phi nodes in our successor block
950 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
951 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +0000952 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000953 auto *Phi = cast<MemoryPhi>(&Accesses->front());
George Burgess IVe1100f52016-02-02 22:46:49 +0000954 Phi->addIncoming(IncomingVal, BB);
955 }
956
957 return IncomingVal;
958}
959
960/// \brief This is the standard SSA renaming algorithm.
961///
962/// We walk the dominator tree in preorder, renaming accesses, and then filling
963/// in phi nodes in our successors.
964void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
965 SmallPtrSet<BasicBlock *, 16> &Visited) {
966 SmallVector<RenamePassData, 32> WorkStack;
967 IncomingVal = renameBlock(Root->getBlock(), IncomingVal);
968 WorkStack.push_back({Root, Root->begin(), IncomingVal});
969 Visited.insert(Root->getBlock());
970
971 while (!WorkStack.empty()) {
972 DomTreeNode *Node = WorkStack.back().DTN;
973 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
974 IncomingVal = WorkStack.back().IncomingVal;
975
976 if (ChildIt == Node->end()) {
977 WorkStack.pop_back();
978 } else {
979 DomTreeNode *Child = *ChildIt;
980 ++WorkStack.back().ChildIt;
981 BasicBlock *BB = Child->getBlock();
982 Visited.insert(BB);
983 IncomingVal = renameBlock(BB, IncomingVal);
984 WorkStack.push_back({Child, Child->begin(), IncomingVal});
985 }
986 }
987}
988
989/// \brief Compute dominator levels, used by the phi insertion algorithm above.
990void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) {
991 for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode());
992 DFI != DFE; ++DFI)
993 DomLevels[*DFI] = DFI.getPathLength() - 1;
994}
995
George Burgess IVa362b092016-07-06 00:28:43 +0000996/// \brief This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +0000997/// unreachable blocks, and marking all other unreachable MemoryAccess's as
998/// being uses of the live on entry definition.
999void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
1000 assert(!DT->isReachableFromEntry(BB) &&
1001 "Reachable block found while handling unreachable blocks");
1002
Daniel Berlinfc7e6512016-07-06 05:32:05 +00001003 // Make sure phi nodes in our reachable successors end up with a
1004 // LiveOnEntryDef for our incoming edge, even though our block is forward
1005 // unreachable. We could just disconnect these blocks from the CFG fully,
1006 // but we do not right now.
1007 for (const BasicBlock *S : successors(BB)) {
1008 if (!DT->isReachableFromEntry(S))
1009 continue;
1010 auto It = PerBlockAccesses.find(S);
1011 // Rename the phi nodes in our successor block
1012 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1013 continue;
1014 AccessList *Accesses = It->second.get();
1015 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1016 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1017 }
1018
George Burgess IVe1100f52016-02-02 22:46:49 +00001019 auto It = PerBlockAccesses.find(BB);
1020 if (It == PerBlockAccesses.end())
1021 return;
1022
1023 auto &Accesses = It->second;
1024 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1025 auto Next = std::next(AI);
1026 // If we have a phi, just remove it. We are going to replace all
1027 // users with live on entry.
1028 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1029 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1030 else
1031 Accesses->erase(AI);
1032 AI = Next;
1033 }
1034}
1035
Geoff Berryb96d3b22016-06-01 21:30:40 +00001036MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
1037 : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
1038 NextID(0) {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001039 buildMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001040}
1041
1042MemorySSA::MemorySSA(MemorySSA &&MSSA)
1043 : AA(MSSA.AA), DT(MSSA.DT), F(MSSA.F),
1044 ValueToMemoryAccess(std::move(MSSA.ValueToMemoryAccess)),
1045 PerBlockAccesses(std::move(MSSA.PerBlockAccesses)),
1046 LiveOnEntryDef(std::move(MSSA.LiveOnEntryDef)),
1047 Walker(std::move(MSSA.Walker)), NextID(MSSA.NextID) {
1048 // Update the Walker MSSA pointer so it doesn't point to the moved-from MSSA
1049 // object any more.
1050 Walker->MSSA = this;
1051}
George Burgess IVe1100f52016-02-02 22:46:49 +00001052
1053MemorySSA::~MemorySSA() {
1054 // Drop all our references
1055 for (const auto &Pair : PerBlockAccesses)
1056 for (MemoryAccess &MA : *Pair.second)
1057 MA.dropAllReferences();
1058}
1059
Daniel Berlin14300262016-06-21 18:39:20 +00001060MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001061 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1062
1063 if (Res.second)
Daniel Berlinada263d2016-06-20 20:21:33 +00001064 Res.first->second = make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001065 return Res.first->second.get();
1066}
1067
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001068void MemorySSA::buildMemorySSA() {
George Burgess IVe1100f52016-02-02 22:46:49 +00001069 // We create an access to represent "live on entry", for things like
1070 // arguments or users of globals, where the memory they use is defined before
1071 // the beginning of the function. We do not actually insert it into the IR.
1072 // We do not define a live on exit for the immediate uses, and thus our
1073 // semantics do *not* imply that something with no immediate uses can simply
1074 // be removed.
1075 BasicBlock &StartingPoint = F.getEntryBlock();
1076 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
1077 &StartingPoint, NextID++);
1078
1079 // We maintain lists of memory accesses per-block, trading memory for time. We
1080 // could just look up the memory access for every possible instruction in the
1081 // stream.
1082 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001083 SmallPtrSet<BasicBlock *, 32> DefUseBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001084 // Go through each block, figure out where defs occur, and chain together all
1085 // the accesses.
1086 for (BasicBlock &B : F) {
Daniel Berlin7898ca62016-02-07 01:52:15 +00001087 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001088 AccessList *Accesses = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001089 for (Instruction &I : B) {
Peter Collingbourneffecb142016-05-26 01:19:17 +00001090 MemoryUseOrDef *MUD = createNewAccess(&I);
George Burgess IVb42b7622016-03-11 19:34:03 +00001091 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001092 continue;
George Burgess IV3887a412016-03-21 21:25:39 +00001093 InsertIntoDef |= isa<MemoryDef>(MUD);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001094
George Burgess IVe1100f52016-02-02 22:46:49 +00001095 if (!Accesses)
1096 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001097 Accesses->push_back(MUD);
George Burgess IVe1100f52016-02-02 22:46:49 +00001098 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001099 if (InsertIntoDef)
1100 DefiningBlocks.insert(&B);
George Burgess IV3887a412016-03-21 21:25:39 +00001101 if (Accesses)
Daniel Berlin1b51a292016-02-07 01:52:19 +00001102 DefUseBlocks.insert(&B);
1103 }
1104
1105 // Compute live-in.
1106 // Live in is normally defined as "all the blocks on the path from each def to
1107 // each of it's uses".
1108 // MemoryDef's are implicit uses of previous state, so they are also uses.
1109 // This means we don't really have def-only instructions. The only
1110 // MemoryDef's that are not really uses are those that are of the LiveOnEntry
1111 // variable (because LiveOnEntry can reach anywhere, and every def is a
1112 // must-kill of LiveOnEntry).
1113 // In theory, you could precisely compute live-in by using alias-analysis to
1114 // disambiguate defs and uses to see which really pair up with which.
1115 // In practice, this would be really expensive and difficult. So we simply
1116 // assume all defs are also uses that need to be kept live.
1117 // Because of this, the end result of this live-in computation will be "the
1118 // entire set of basic blocks that reach any use".
1119
1120 SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
1121 SmallVector<BasicBlock *, 64> LiveInBlockWorklist(DefUseBlocks.begin(),
1122 DefUseBlocks.end());
1123 // Now that we have a set of blocks where a value is live-in, recursively add
1124 // predecessors until we find the full region the value is live.
1125 while (!LiveInBlockWorklist.empty()) {
1126 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
1127
1128 // The block really is live in here, insert it into the set. If already in
1129 // the set, then it has already been processed.
1130 if (!LiveInBlocks.insert(BB).second)
1131 continue;
1132
1133 // Since the value is live into BB, it is either defined in a predecessor or
1134 // live into it to.
1135 LiveInBlockWorklist.append(pred_begin(BB), pred_end(BB));
George Burgess IVe1100f52016-02-02 22:46:49 +00001136 }
1137
1138 // Determine where our MemoryPhi's should go
Daniel Berlin77fa84e2016-04-19 06:13:28 +00001139 ForwardIDFCalculator IDFs(*DT);
George Burgess IVe1100f52016-02-02 22:46:49 +00001140 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001141 IDFs.setLiveInBlocks(LiveInBlocks);
George Burgess IVe1100f52016-02-02 22:46:49 +00001142 SmallVector<BasicBlock *, 32> IDFBlocks;
1143 IDFs.calculate(IDFBlocks);
1144
1145 // Now place MemoryPhi nodes.
1146 for (auto &BB : IDFBlocks) {
1147 // Insert phi node
Daniel Berlinada263d2016-06-20 20:21:33 +00001148 AccessList *Accesses = getOrCreateAccessList(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001149 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlinf6c9ae92016-02-10 17:41:25 +00001150 ValueToMemoryAccess.insert(std::make_pair(BB, Phi));
George Burgess IVe1100f52016-02-02 22:46:49 +00001151 // Phi's always are placed at the front of the block.
1152 Accesses->push_front(Phi);
1153 }
1154
1155 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1156 // filled in with all blocks.
1157 SmallPtrSet<BasicBlock *, 16> Visited;
1158 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1159
George Burgess IV5f308972016-07-19 01:29:15 +00001160 CachingWalker *Walker = getWalkerImpl();
1161
1162 // We're doing a batch of updates; don't drop useful caches between them.
1163 Walker->setAutoResetWalker(false);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001164
George Burgess IVe1100f52016-02-02 22:46:49 +00001165 // Now optimize the MemoryUse's defining access to point to the nearest
1166 // dominating clobbering def.
1167 // This ensures that MemoryUse's that are killed by the same store are
1168 // immediate users of that store, one of the invariants we guarantee.
1169 for (auto DomNode : depth_first(DT)) {
1170 BasicBlock *BB = DomNode->getBlock();
1171 auto AI = PerBlockAccesses.find(BB);
1172 if (AI == PerBlockAccesses.end())
1173 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +00001174 AccessList *Accesses = AI->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001175 for (auto &MA : *Accesses) {
1176 if (auto *MU = dyn_cast<MemoryUse>(&MA)) {
1177 Instruction *Inst = MU->getMemoryInst();
Daniel Berlin64120022016-03-02 21:16:28 +00001178 MU->setDefiningAccess(Walker->getClobberingMemoryAccess(Inst));
George Burgess IVe1100f52016-02-02 22:46:49 +00001179 }
1180 }
1181 }
1182
George Burgess IV5f308972016-07-19 01:29:15 +00001183 Walker->setAutoResetWalker(true);
1184 Walker->resetClobberWalker();
1185
George Burgess IVe1100f52016-02-02 22:46:49 +00001186 // Mark the uses in unreachable blocks as live on entry, so that they go
1187 // somewhere.
1188 for (auto &BB : F)
1189 if (!Visited.count(&BB))
1190 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001191}
George Burgess IVe1100f52016-02-02 22:46:49 +00001192
George Burgess IV5f308972016-07-19 01:29:15 +00001193MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1194
1195MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001196 if (Walker)
1197 return Walker.get();
1198
1199 Walker = make_unique<CachingWalker>(this, AA, DT);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001200 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001201}
1202
Daniel Berlin14300262016-06-21 18:39:20 +00001203MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1204 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
1205 AccessList *Accesses = getOrCreateAccessList(BB);
1206 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
1207 ValueToMemoryAccess.insert(std::make_pair(BB, Phi));
1208 // Phi's always are placed at the front of the block.
1209 Accesses->push_front(Phi);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001210 BlockNumberingValid.erase(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001211 return Phi;
1212}
1213
1214MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
1215 MemoryAccess *Definition) {
1216 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1217 MemoryUseOrDef *NewAccess = createNewAccess(I);
1218 assert(
1219 NewAccess != nullptr &&
1220 "Tried to create a memory access for a non-memory touching instruction");
1221 NewAccess->setDefiningAccess(Definition);
1222 return NewAccess;
1223}
1224
1225MemoryAccess *MemorySSA::createMemoryAccessInBB(Instruction *I,
1226 MemoryAccess *Definition,
1227 const BasicBlock *BB,
1228 InsertionPlace Point) {
1229 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1230 auto *Accesses = getOrCreateAccessList(BB);
1231 if (Point == Beginning) {
1232 // It goes after any phi nodes
1233 auto AI = std::find_if(
1234 Accesses->begin(), Accesses->end(),
1235 [](const MemoryAccess &MA) { return !isa<MemoryPhi>(MA); });
1236
1237 Accesses->insert(AI, NewAccess);
1238 } else {
1239 Accesses->push_back(NewAccess);
1240 }
Daniel Berlin5c46b942016-07-19 22:49:43 +00001241 BlockNumberingValid.erase(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001242 return NewAccess;
1243}
1244MemoryAccess *MemorySSA::createMemoryAccessBefore(Instruction *I,
1245 MemoryAccess *Definition,
1246 MemoryAccess *InsertPt) {
1247 assert(I->getParent() == InsertPt->getBlock() &&
1248 "New and old access must be in the same block");
1249 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1250 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
1251 Accesses->insert(AccessList::iterator(InsertPt), NewAccess);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001252 BlockNumberingValid.erase(InsertPt->getBlock());
Daniel Berlin14300262016-06-21 18:39:20 +00001253 return NewAccess;
1254}
1255
1256MemoryAccess *MemorySSA::createMemoryAccessAfter(Instruction *I,
1257 MemoryAccess *Definition,
1258 MemoryAccess *InsertPt) {
1259 assert(I->getParent() == InsertPt->getBlock() &&
1260 "New and old access must be in the same block");
1261 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1262 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
1263 Accesses->insertAfter(AccessList::iterator(InsertPt), NewAccess);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001264 BlockNumberingValid.erase(InsertPt->getBlock());
Daniel Berlin14300262016-06-21 18:39:20 +00001265 return NewAccess;
1266}
1267
George Burgess IVe1100f52016-02-02 22:46:49 +00001268/// \brief Helper function to create new memory accesses
Peter Collingbourneffecb142016-05-26 01:19:17 +00001269MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001270 // The assume intrinsic has a control dependency which we model by claiming
1271 // that it writes arbitrarily. Ignore that fake memory dependency here.
1272 // FIXME: Replace this special casing with a more accurate modelling of
1273 // assume's control dependency.
1274 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1275 if (II->getIntrinsicID() == Intrinsic::assume)
1276 return nullptr;
1277
George Burgess IVe1100f52016-02-02 22:46:49 +00001278 // Find out what affect this instruction has on memory.
1279 ModRefInfo ModRef = AA->getModRefInfo(I);
1280 bool Def = bool(ModRef & MRI_Mod);
1281 bool Use = bool(ModRef & MRI_Ref);
1282
1283 // It's possible for an instruction to not modify memory at all. During
1284 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +00001285 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +00001286 return nullptr;
1287
1288 assert((Def || Use) &&
1289 "Trying to create a memory access with a non-memory instruction");
1290
George Burgess IVb42b7622016-03-11 19:34:03 +00001291 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001292 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +00001293 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +00001294 else
George Burgess IVb42b7622016-03-11 19:34:03 +00001295 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
1296 ValueToMemoryAccess.insert(std::make_pair(I, MUD));
1297 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001298}
1299
1300MemoryAccess *MemorySSA::findDominatingDef(BasicBlock *UseBlock,
1301 enum InsertionPlace Where) {
1302 // Handle the initial case
1303 if (Where == Beginning)
1304 // The only thing that could define us at the beginning is a phi node
1305 if (MemoryPhi *Phi = getMemoryAccess(UseBlock))
1306 return Phi;
1307
1308 DomTreeNode *CurrNode = DT->getNode(UseBlock);
1309 // Need to be defined by our dominator
1310 if (Where == Beginning)
1311 CurrNode = CurrNode->getIDom();
1312 Where = End;
1313 while (CurrNode) {
1314 auto It = PerBlockAccesses.find(CurrNode->getBlock());
1315 if (It != PerBlockAccesses.end()) {
1316 auto &Accesses = It->second;
David Majnemerd7708772016-06-24 04:05:21 +00001317 for (MemoryAccess &RA : reverse(*Accesses)) {
1318 if (isa<MemoryDef>(RA) || isa<MemoryPhi>(RA))
1319 return &RA;
George Burgess IVe1100f52016-02-02 22:46:49 +00001320 }
1321 }
1322 CurrNode = CurrNode->getIDom();
1323 }
1324 return LiveOnEntryDef.get();
1325}
1326
1327/// \brief Returns true if \p Replacer dominates \p Replacee .
1328bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1329 const MemoryAccess *Replacee) const {
1330 if (isa<MemoryUseOrDef>(Replacee))
1331 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1332 const auto *MP = cast<MemoryPhi>(Replacee);
1333 // For a phi node, the use occurs in the predecessor block of the phi node.
1334 // Since we may occur multiple times in the phi node, we have to check each
1335 // operand to ensure Replacer dominates each operand where Replacee occurs.
1336 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +00001337 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +00001338 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1339 return false;
1340 }
1341 return true;
1342}
1343
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001344/// \brief If all arguments of a MemoryPHI are defined by the same incoming
1345/// argument, return that argument.
1346static MemoryAccess *onlySingleValue(MemoryPhi *MP) {
1347 MemoryAccess *MA = nullptr;
1348
1349 for (auto &Arg : MP->operands()) {
1350 if (!MA)
1351 MA = cast<MemoryAccess>(Arg);
1352 else if (MA != Arg)
1353 return nullptr;
1354 }
1355 return MA;
1356}
1357
1358/// \brief Properly remove \p MA from all of MemorySSA's lookup tables.
1359///
1360/// Because of the way the intrusive list and use lists work, it is important to
1361/// do removal in the right order.
1362void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1363 assert(MA->use_empty() &&
1364 "Trying to remove memory access that still has uses");
Daniel Berlin5c46b942016-07-19 22:49:43 +00001365 BlockNumbering.erase(MA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001366 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
1367 MUD->setDefiningAccess(nullptr);
1368 // Invalidate our walker's cache if necessary
1369 if (!isa<MemoryUse>(MA))
1370 Walker->invalidateInfo(MA);
1371 // The call below to erase will destroy MA, so we can't change the order we
1372 // are doing things here
1373 Value *MemoryInst;
1374 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1375 MemoryInst = MUD->getMemoryInst();
1376 } else {
1377 MemoryInst = MA->getBlock();
1378 }
1379 ValueToMemoryAccess.erase(MemoryInst);
1380
George Burgess IVe0e6e482016-03-02 02:35:04 +00001381 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
Daniel Berlinada263d2016-06-20 20:21:33 +00001382 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001383 Accesses->erase(MA);
George Burgess IVe0e6e482016-03-02 02:35:04 +00001384 if (Accesses->empty())
1385 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001386}
1387
1388void MemorySSA::removeMemoryAccess(MemoryAccess *MA) {
1389 assert(!isLiveOnEntryDef(MA) && "Trying to remove the live on entry def");
1390 // We can only delete phi nodes if they have no uses, or we can replace all
1391 // uses with a single definition.
1392 MemoryAccess *NewDefTarget = nullptr;
1393 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) {
1394 // Note that it is sufficient to know that all edges of the phi node have
1395 // the same argument. If they do, by the definition of dominance frontiers
1396 // (which we used to place this phi), that argument must dominate this phi,
1397 // and thus, must dominate the phi's uses, and so we will not hit the assert
1398 // below.
1399 NewDefTarget = onlySingleValue(MP);
1400 assert((NewDefTarget || MP->use_empty()) &&
1401 "We can't delete this memory phi");
1402 } else {
1403 NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
1404 }
1405
1406 // Re-point the uses at our defining access
1407 if (!MA->use_empty())
1408 MA->replaceAllUsesWith(NewDefTarget);
1409
1410 // The call below to erase will destroy MA, so we can't change the order we
1411 // are doing things here
1412 removeFromLookups(MA);
1413}
1414
George Burgess IVe1100f52016-02-02 22:46:49 +00001415void MemorySSA::print(raw_ostream &OS) const {
1416 MemorySSAAnnotatedWriter Writer(this);
1417 F.print(OS, &Writer);
1418}
1419
1420void MemorySSA::dump() const {
1421 MemorySSAAnnotatedWriter Writer(this);
1422 F.print(dbgs(), &Writer);
1423}
1424
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001425void MemorySSA::verifyMemorySSA() const {
1426 verifyDefUses(F);
1427 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001428 verifyOrdering(F);
1429}
1430
1431/// \brief Verify that the order and existence of MemoryAccesses matches the
1432/// order and existence of memory affecting instructions.
1433void MemorySSA::verifyOrdering(Function &F) const {
1434 // Walk all the blocks, comparing what the lookups think and what the access
1435 // lists think, as well as the order in the blocks vs the order in the access
1436 // lists.
1437 SmallVector<MemoryAccess *, 32> ActualAccesses;
1438 for (BasicBlock &B : F) {
1439 const AccessList *AL = getBlockAccesses(&B);
1440 MemoryAccess *Phi = getMemoryAccess(&B);
1441 if (Phi)
1442 ActualAccesses.push_back(Phi);
1443 for (Instruction &I : B) {
1444 MemoryAccess *MA = getMemoryAccess(&I);
1445 assert((!MA || AL) && "We have memory affecting instructions "
1446 "in this block but they are not in the "
1447 "access list");
1448 if (MA)
1449 ActualAccesses.push_back(MA);
1450 }
1451 // Either we hit the assert, really have no accesses, or we have both
1452 // accesses and an access list
1453 if (!AL)
1454 continue;
1455 assert(AL->size() == ActualAccesses.size() &&
1456 "We don't have the same number of accesses in the block as on the "
1457 "access list");
1458 auto ALI = AL->begin();
1459 auto AAI = ActualAccesses.begin();
1460 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1461 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1462 ++ALI;
1463 ++AAI;
1464 }
1465 ActualAccesses.clear();
1466 }
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001467}
1468
George Burgess IVe1100f52016-02-02 22:46:49 +00001469/// \brief Verify the domination properties of MemorySSA by checking that each
1470/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001471void MemorySSA::verifyDomination(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001472 for (BasicBlock &B : F) {
1473 // Phi nodes are attached to basic blocks
1474 if (MemoryPhi *MP = getMemoryAccess(&B)) {
1475 for (User *U : MP->users()) {
1476 BasicBlock *UseBlock;
1477 // Phi operands are used on edges, we simulate the right domination by
1478 // acting as if the use occurred at the end of the predecessor block.
1479 if (MemoryPhi *P = dyn_cast<MemoryPhi>(U)) {
1480 for (const auto &Arg : P->operands()) {
1481 if (Arg == MP) {
1482 UseBlock = P->getIncomingBlock(Arg);
1483 break;
1484 }
1485 }
1486 } else {
1487 UseBlock = cast<MemoryAccess>(U)->getBlock();
1488 }
George Burgess IV60adac42016-02-02 23:26:01 +00001489 (void)UseBlock;
George Burgess IVe1100f52016-02-02 22:46:49 +00001490 assert(DT->dominates(MP->getBlock(), UseBlock) &&
1491 "Memory PHI does not dominate it's uses");
1492 }
1493 }
1494
1495 for (Instruction &I : B) {
1496 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
1497 if (!MD)
1498 continue;
1499
Benjamin Kramer451f54c2016-02-22 13:11:58 +00001500 for (User *U : MD->users()) {
Daniel Berlinada263d2016-06-20 20:21:33 +00001501 BasicBlock *UseBlock;
1502 (void)UseBlock;
George Burgess IVe1100f52016-02-02 22:46:49 +00001503 // Things are allowed to flow to phi nodes over their predecessor edge.
1504 if (auto *P = dyn_cast<MemoryPhi>(U)) {
1505 for (const auto &Arg : P->operands()) {
1506 if (Arg == MD) {
1507 UseBlock = P->getIncomingBlock(Arg);
1508 break;
1509 }
1510 }
1511 } else {
1512 UseBlock = cast<MemoryAccess>(U)->getBlock();
1513 }
1514 assert(DT->dominates(MD->getBlock(), UseBlock) &&
1515 "Memory Def does not dominate it's uses");
1516 }
1517 }
1518 }
1519}
1520
1521/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
1522/// appears in the use list of \p Def.
1523///
1524/// llvm_unreachable is used instead of asserts because this may be called in
1525/// a build without asserts. In that case, we don't want this to turn into a
1526/// nop.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001527void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001528 // The live on entry use may cause us to get a NULL def here
1529 if (!Def) {
1530 if (!isLiveOnEntryDef(Use))
1531 llvm_unreachable("Null def but use not point to live on entry def");
1532 } else if (std::find(Def->user_begin(), Def->user_end(), Use) ==
1533 Def->user_end()) {
1534 llvm_unreachable("Did not find use in def's use list");
1535 }
1536}
1537
1538/// \brief Verify the immediate use information, by walking all the memory
1539/// accesses and verifying that, for each use, it appears in the
1540/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001541void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001542 for (BasicBlock &B : F) {
1543 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00001544 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00001545 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
1546 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00001547 "Incomplete MemoryPhi Node");
George Burgess IVe1100f52016-02-02 22:46:49 +00001548 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1549 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Daniel Berlin14300262016-06-21 18:39:20 +00001550 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001551
1552 for (Instruction &I : B) {
1553 if (MemoryAccess *MA = getMemoryAccess(&I)) {
1554 assert(isa<MemoryUseOrDef>(MA) &&
1555 "Found a phi node not attached to a bb");
1556 verifyUseInDefs(cast<MemoryUseOrDef>(MA)->getDefiningAccess(), MA);
1557 }
1558 }
1559 }
1560}
1561
1562MemoryAccess *MemorySSA::getMemoryAccess(const Value *I) const {
Daniel Berlinf6c9ae92016-02-10 17:41:25 +00001563 return ValueToMemoryAccess.lookup(I);
George Burgess IVe1100f52016-02-02 22:46:49 +00001564}
1565
1566MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
1567 return cast_or_null<MemoryPhi>(getMemoryAccess((const Value *)BB));
1568}
1569
Daniel Berlin5c46b942016-07-19 22:49:43 +00001570/// Perform a local numbering on blocks so that instruction ordering can be
1571/// determined in constant time.
1572/// TODO: We currently just number in order. If we numbered by N, we could
1573/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
1574/// log2(N) sequences of mixed before and after) without needing to invalidate
1575/// the numbering.
1576void MemorySSA::renumberBlock(const BasicBlock *B) const {
1577 // The pre-increment ensures the numbers really start at 1.
1578 unsigned long CurrentNumber = 0;
1579 const AccessList *AL = getBlockAccesses(B);
1580 assert(AL != nullptr && "Asking to renumber an empty block");
1581 for (const auto &I : *AL)
1582 BlockNumbering[&I] = ++CurrentNumber;
1583 BlockNumberingValid.insert(B);
1584}
1585
George Burgess IVe1100f52016-02-02 22:46:49 +00001586/// \brief Determine, for two memory accesses in the same block,
1587/// whether \p Dominator dominates \p Dominatee.
1588/// \returns True if \p Dominator dominates \p Dominatee.
1589bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
1590 const MemoryAccess *Dominatee) const {
Sebastian Pope1f60b12016-06-10 21:36:41 +00001591
Daniel Berlin5c46b942016-07-19 22:49:43 +00001592 const BasicBlock *DominatorBlock = Dominator->getBlock();
Daniel Berlin5c46b942016-07-19 22:49:43 +00001593
Daniel Berlin19860302016-07-19 23:08:08 +00001594 assert((DominatorBlock == Dominatee->getBlock()) &&
Daniel Berlin5c46b942016-07-19 22:49:43 +00001595 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00001596 // A node dominates itself.
1597 if (Dominatee == Dominator)
1598 return true;
1599
1600 // When Dominatee is defined on function entry, it is not dominated by another
1601 // memory access.
1602 if (isLiveOnEntryDef(Dominatee))
1603 return false;
1604
1605 // When Dominator is defined on function entry, it dominates the other memory
1606 // access.
1607 if (isLiveOnEntryDef(Dominator))
1608 return true;
1609
Daniel Berlin5c46b942016-07-19 22:49:43 +00001610 if (!BlockNumberingValid.count(DominatorBlock))
1611 renumberBlock(DominatorBlock);
George Burgess IVe1100f52016-02-02 22:46:49 +00001612
Daniel Berlin5c46b942016-07-19 22:49:43 +00001613 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
1614 // All numbers start with 1
1615 assert(DominatorNum != 0 && "Block was not numbered properly");
1616 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
1617 assert(DominateeNum != 0 && "Block was not numbered properly");
1618 return DominatorNum < DominateeNum;
George Burgess IVe1100f52016-02-02 22:46:49 +00001619}
1620
George Burgess IV5f308972016-07-19 01:29:15 +00001621bool MemorySSA::dominates(const MemoryAccess *Dominator,
1622 const MemoryAccess *Dominatee) const {
1623 if (Dominator == Dominatee)
1624 return true;
1625
1626 if (isLiveOnEntryDef(Dominatee))
1627 return false;
1628
1629 if (Dominator->getBlock() != Dominatee->getBlock())
1630 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
1631 return locallyDominates(Dominator, Dominatee);
1632}
1633
George Burgess IVe1100f52016-02-02 22:46:49 +00001634const static char LiveOnEntryStr[] = "liveOnEntry";
1635
1636void MemoryDef::print(raw_ostream &OS) const {
1637 MemoryAccess *UO = getDefiningAccess();
1638
1639 OS << getID() << " = MemoryDef(";
1640 if (UO && UO->getID())
1641 OS << UO->getID();
1642 else
1643 OS << LiveOnEntryStr;
1644 OS << ')';
1645}
1646
1647void MemoryPhi::print(raw_ostream &OS) const {
1648 bool First = true;
1649 OS << getID() << " = MemoryPhi(";
1650 for (const auto &Op : operands()) {
1651 BasicBlock *BB = getIncomingBlock(Op);
1652 MemoryAccess *MA = cast<MemoryAccess>(Op);
1653 if (!First)
1654 OS << ',';
1655 else
1656 First = false;
1657
1658 OS << '{';
1659 if (BB->hasName())
1660 OS << BB->getName();
1661 else
1662 BB->printAsOperand(OS, false);
1663 OS << ',';
1664 if (unsigned ID = MA->getID())
1665 OS << ID;
1666 else
1667 OS << LiveOnEntryStr;
1668 OS << '}';
1669 }
1670 OS << ')';
1671}
1672
1673MemoryAccess::~MemoryAccess() {}
1674
1675void MemoryUse::print(raw_ostream &OS) const {
1676 MemoryAccess *UO = getDefiningAccess();
1677 OS << "MemoryUse(";
1678 if (UO && UO->getID())
1679 OS << UO->getID();
1680 else
1681 OS << LiveOnEntryStr;
1682 OS << ')';
1683}
1684
1685void MemoryAccess::dump() const {
1686 print(dbgs());
1687 dbgs() << "\n";
1688}
1689
Chad Rosier232e29e2016-07-06 21:20:47 +00001690char MemorySSAPrinterLegacyPass::ID = 0;
1691
1692MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
1693 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
1694}
1695
1696void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
1697 AU.setPreservesAll();
1698 AU.addRequired<MemorySSAWrapperPass>();
1699 AU.addPreserved<MemorySSAWrapperPass>();
1700}
1701
1702bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
1703 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
1704 MSSA.print(dbgs());
1705 if (VerifyMemorySSA)
1706 MSSA.verifyMemorySSA();
1707 return false;
1708}
1709
Geoff Berryb96d3b22016-06-01 21:30:40 +00001710char MemorySSAAnalysis::PassID;
George Burgess IVe1100f52016-02-02 22:46:49 +00001711
Geoff Berryb96d3b22016-06-01 21:30:40 +00001712MemorySSA MemorySSAAnalysis::run(Function &F, AnalysisManager<Function> &AM) {
1713 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1714 auto &AA = AM.getResult<AAManager>(F);
1715 return MemorySSA(F, &AA, &DT);
George Burgess IVe1100f52016-02-02 22:46:49 +00001716}
1717
Geoff Berryb96d3b22016-06-01 21:30:40 +00001718PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
1719 FunctionAnalysisManager &AM) {
1720 OS << "MemorySSA for function: " << F.getName() << "\n";
1721 AM.getResult<MemorySSAAnalysis>(F).print(OS);
1722
1723 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00001724}
1725
Geoff Berryb96d3b22016-06-01 21:30:40 +00001726PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
1727 FunctionAnalysisManager &AM) {
1728 AM.getResult<MemorySSAAnalysis>(F).verifyMemorySSA();
1729
1730 return PreservedAnalyses::all();
1731}
1732
1733char MemorySSAWrapperPass::ID = 0;
1734
1735MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
1736 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
1737}
1738
1739void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
1740
1741void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001742 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001743 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
1744 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001745}
1746
Geoff Berryb96d3b22016-06-01 21:30:40 +00001747bool MemorySSAWrapperPass::runOnFunction(Function &F) {
1748 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1749 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1750 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00001751 return false;
1752}
1753
Geoff Berryb96d3b22016-06-01 21:30:40 +00001754void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00001755
Geoff Berryb96d3b22016-06-01 21:30:40 +00001756void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001757 MSSA->print(OS);
1758}
1759
George Burgess IVe1100f52016-02-02 22:46:49 +00001760MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
1761
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001762MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A,
1763 DominatorTree *D)
Daniel Berlin5c46b942016-07-19 22:49:43 +00001764 : MemorySSAWalker(M), Walker(*M, *A, *D, Cache), AutoResetWalker(true) {}
George Burgess IVe1100f52016-02-02 22:46:49 +00001765
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001766MemorySSA::CachingWalker::~CachingWalker() {}
George Burgess IVe1100f52016-02-02 22:46:49 +00001767
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001768void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) {
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001769 // TODO: We can do much better cache invalidation with differently stored
1770 // caches. For now, for MemoryUses, we simply remove them
1771 // from the cache, and kill the entire call/non-call cache for everything
1772 // else. The problem is for phis or defs, currently we'd need to follow use
1773 // chains down and invalidate anything below us in the chain that currently
1774 // terminates at this access.
1775
1776 // See if this is a MemoryUse, if so, just remove the cached info. MemoryUse
1777 // is by definition never a barrier, so nothing in the cache could point to
1778 // this use. In that case, we only need invalidate the info for the use
1779 // itself.
1780
1781 if (MemoryUse *MU = dyn_cast<MemoryUse>(MA)) {
George Burgess IV5f308972016-07-19 01:29:15 +00001782 UpwardsMemoryQuery Q(MU->getMemoryInst(), MU);
1783 Cache.remove(MU, Q.StartingLoc, Q.IsCall);
Geoff Berry9fe26e62016-04-22 14:44:10 +00001784 } else {
1785 // 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 +00001786 Cache.clear();
Geoff Berry9fe26e62016-04-22 14:44:10 +00001787 }
1788
Filipe Cabecinhas0da99372016-04-29 15:22:48 +00001789#ifdef EXPENSIVE_CHECKS
Geoff Berry9fe26e62016-04-22 14:44:10 +00001790 verifyRemoved(MA);
1791#endif
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001792}
1793
George Burgess IVe1100f52016-02-02 22:46:49 +00001794/// \brief Walk the use-def chains starting at \p MA and find
1795/// the MemoryAccess that actually clobbers Loc.
1796///
1797/// \returns our clobbering memory access
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001798MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
1799 MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +00001800 MemoryAccess *New = Walker.findClobber(StartingAccess, Q);
1801#ifdef EXPENSIVE_CHECKS
1802 MemoryAccess *NewNoCache =
1803 Walker.findClobber(StartingAccess, Q, /*UseWalkerCache=*/false);
1804 assert(NewNoCache == New && "Cache made us hand back a different result?");
1805#endif
1806 if (AutoResetWalker)
1807 resetClobberWalker();
1808 return New;
George Burgess IVe1100f52016-02-02 22:46:49 +00001809}
1810
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001811MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
1812 MemoryAccess *StartingAccess, MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001813 if (isa<MemoryPhi>(StartingAccess))
1814 return StartingAccess;
1815
1816 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
1817 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
1818 return StartingUseOrDef;
1819
1820 Instruction *I = StartingUseOrDef->getMemoryInst();
1821
1822 // Conservatively, fences are always clobbers, so don't perform the walk if we
1823 // hit a fence.
David Majnemera940f362016-07-15 17:19:24 +00001824 if (!ImmutableCallSite(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00001825 return StartingUseOrDef;
1826
1827 UpwardsMemoryQuery Q;
1828 Q.OriginalAccess = StartingUseOrDef;
1829 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00001830 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00001831 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00001832
George Burgess IV5f308972016-07-19 01:29:15 +00001833 if (auto *CacheResult = Cache.lookup(StartingUseOrDef, Loc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00001834 return CacheResult;
1835
1836 // Unlike the other function, do not walk to the def of a def, because we are
1837 // handed something we already believe is the clobbering access.
1838 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
1839 ? StartingUseOrDef->getDefiningAccess()
1840 : StartingUseOrDef;
1841
1842 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00001843 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
1844 DEBUG(dbgs() << *StartingUseOrDef << "\n");
1845 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
1846 DEBUG(dbgs() << *Clobber << "\n");
1847 return Clobber;
1848}
1849
1850MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00001851MemorySSA::CachingWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
1852 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
1853 // If this is a MemoryPhi, we can't do anything.
1854 if (!StartingAccess)
1855 return MA;
George Burgess IVe1100f52016-02-02 22:46:49 +00001856
George Burgess IV400ae402016-07-20 19:51:34 +00001857 const Instruction *I = StartingAccess->getMemoryInst();
George Burgess IV5f308972016-07-19 01:29:15 +00001858 UpwardsMemoryQuery Q(I, StartingAccess);
David Majnemera940f362016-07-15 17:19:24 +00001859 // We can't sanely do anything with a fences, they conservatively
George Burgess IVe1100f52016-02-02 22:46:49 +00001860 // clobber all memory, and have no locations to get pointers from to
David Majnemera940f362016-07-15 17:19:24 +00001861 // try to disambiguate.
George Burgess IV5f308972016-07-19 01:29:15 +00001862 if (!Q.IsCall && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00001863 return StartingAccess;
1864
George Burgess IV5f308972016-07-19 01:29:15 +00001865 if (auto *CacheResult = Cache.lookup(StartingAccess, Q.StartingLoc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00001866 return CacheResult;
1867
1868 // Start with the thing we already think clobbers this location
1869 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
1870
1871 // At this point, DefiningAccess may be the live on entry def.
1872 // If it is, we will not get a better result.
1873 if (MSSA->isLiveOnEntryDef(DefiningAccess))
1874 return DefiningAccess;
1875
1876 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00001877 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
1878 DEBUG(dbgs() << *DefiningAccess << "\n");
1879 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
1880 DEBUG(dbgs() << *Result << "\n");
1881
1882 return Result;
1883}
1884
Geoff Berry9fe26e62016-04-22 14:44:10 +00001885// Verify that MA doesn't exist in any of the caches.
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001886void MemorySSA::CachingWalker::verifyRemoved(MemoryAccess *MA) {
George Burgess IV5f308972016-07-19 01:29:15 +00001887 assert(!Cache.contains(MA) && "Found removed MemoryAccess in cache.");
Geoff Berry9fe26e62016-04-22 14:44:10 +00001888}
1889
George Burgess IVe1100f52016-02-02 22:46:49 +00001890MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00001891DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001892 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
1893 return Use->getDefiningAccess();
1894 return MA;
1895}
1896
1897MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
1898 MemoryAccess *StartingAccess, MemoryLocation &) {
1899 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
1900 return Use->getDefiningAccess();
1901 return StartingAccess;
1902}
George Burgess IV5f308972016-07-19 01:29:15 +00001903} // namespace llvm