blob: e304084251d9be7f140c0e64201392f9cdb070aa [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 {
Daniel Berlin5c46b942016-07-19 22:49:43 +0000339// EXPENSIVE_CHECKS because most of these queries are redundant.
George Burgess IV5f308972016-07-19 01:29:15 +0000340#ifdef EXPENSIVE_CHECKS
341 assert(MSSA.dominates(To, What));
342#endif
343 if (shouldIgnoreCache())
344 return;
345 WC.insert(What, To, Loc, Query->IsCall);
346 }
347
348 MemoryAccess *lookupCache(const MemoryAccess *MA, const MemoryLocation &Loc) {
349 return shouldIgnoreCache() ? nullptr : WC.lookup(MA, Loc, Query->IsCall);
350 }
351
352 void cacheDefPath(const DefPath &DN, MemoryAccess *Target) const {
353 if (shouldIgnoreCache())
354 return;
355
356 for (MemoryAccess *MA : def_chain(DN.First, DN.Last))
357 addCacheEntry(MA, Target, DN.Loc);
358
359 // DefPaths only express the path we walked. So, DN.Last could either be a
360 // thing we want to cache, or not.
361 if (DN.Last != Target)
362 addCacheEntry(DN.Last, Target, DN.Loc);
363 }
364
365 /// Find the nearest def or phi that `From` can legally be optimized to.
366 ///
367 /// FIXME: Deduplicate this with MSSA::findDominatingDef. Ideally, MSSA should
368 /// keep track of this information for us, and allow us O(1) lookups of this
369 /// info.
370 MemoryAccess *getWalkTarget(const MemoryPhi *From) {
George Burgess IV5f308972016-07-19 01:29:15 +0000371 assert(From->getNumOperands() && "Phi with no operands?");
372
373 BasicBlock *BB = From->getBlock();
374 auto At = WalkTargetCache.find(BB);
375 if (At != WalkTargetCache.end())
376 return At->second;
377
378 SmallVector<const BasicBlock *, 8> ToCache;
379 ToCache.push_back(BB);
380
381 MemoryAccess *Result = MSSA.getLiveOnEntryDef();
382 DomTreeNode *Node = DT.getNode(BB);
383 while ((Node = Node->getIDom())) {
384 auto At = WalkTargetCache.find(BB);
385 if (At != WalkTargetCache.end()) {
386 Result = At->second;
387 break;
388 }
389
390 auto *Accesses = MSSA.getBlockAccesses(Node->getBlock());
391 if (Accesses) {
392 auto Iter = find_if(reverse(*Accesses), [](const MemoryAccess &MA) {
393 return !isa<MemoryUse>(MA);
394 });
395 if (Iter != Accesses->rend()) {
396 Result = const_cast<MemoryAccess *>(&*Iter);
397 break;
398 }
399 }
400
401 ToCache.push_back(Node->getBlock());
402 }
403
404 for (const BasicBlock *BB : ToCache)
405 WalkTargetCache.insert({BB, Result});
406 return Result;
407 }
408
409 /// Result of calling walkToPhiOrClobber.
410 struct UpwardsWalkResult {
411 /// The "Result" of the walk. Either a clobber, the last thing we walked, or
412 /// both.
413 MemoryAccess *Result;
414 bool IsKnownClobber;
415 bool FromCache;
416 };
417
418 /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
419 /// This will update Desc.Last as it walks. It will (optionally) also stop at
420 /// StopAt.
421 ///
422 /// This does not test for whether StopAt is a clobber
423 UpwardsWalkResult walkToPhiOrClobber(DefPath &Desc,
424 MemoryAccess *StopAt = nullptr) {
425 assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
426
427 for (MemoryAccess *Current : def_chain(Desc.Last)) {
428 Desc.Last = Current;
429 if (Current == StopAt)
430 return {Current, false, false};
431
432 if (auto *MD = dyn_cast<MemoryDef>(Current))
433 if (MSSA.isLiveOnEntryDef(MD) ||
434 instructionClobbersQuery(MD, Desc.Loc, *Query, AA))
435 return {MD, true, false};
436
437 // Cache checks must be done last, because if Current is a clobber, the
438 // cache will contain the clobber for Current.
439 if (MemoryAccess *MA = lookupCache(Current, Desc.Loc))
440 return {MA, true, true};
441 }
442
443 assert(isa<MemoryPhi>(Desc.Last) &&
444 "Ended at a non-clobber that's not a phi?");
445 return {Desc.Last, false, false};
446 }
447
448 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
449 ListIndex PriorNode) {
450 auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),
451 upward_defs_end());
452 for (const MemoryAccessPair &P : UpwardDefs) {
453 PausedSearches.push_back(Paths.size());
454 Paths.emplace_back(P.second, P.first, PriorNode);
455 }
456 }
457
458 /// Represents a search that terminated after finding a clobber. This clobber
459 /// may or may not be present in the path of defs from LastNode..SearchStart,
460 /// since it may have been retrieved from cache.
461 struct TerminatedPath {
462 MemoryAccess *Clobber;
463 ListIndex LastNode;
464 };
465
466 /// Get an access that keeps us from optimizing to the given phi.
467 ///
468 /// PausedSearches is an array of indices into the Paths array. Its incoming
469 /// value is the indices of searches that stopped at the last phi optimization
470 /// target. It's left in an unspecified state.
471 ///
472 /// If this returns None, NewPaused is a vector of searches that terminated
473 /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
474 Optional<ListIndex>
475 getBlockingAccess(MemoryAccess *StopWhere,
476 SmallVectorImpl<ListIndex> &PausedSearches,
477 SmallVectorImpl<ListIndex> &NewPaused,
478 SmallVectorImpl<TerminatedPath> &Terminated) {
479 assert(!PausedSearches.empty() && "No searches to continue?");
480
481 // BFS vs DFS really doesn't make a difference here, so just do a DFS with
482 // PausedSearches as our stack.
483 while (!PausedSearches.empty()) {
484 ListIndex PathIndex = PausedSearches.pop_back_val();
485 DefPath &Node = Paths[PathIndex];
486
487 // If we've already visited this path with this MemoryLocation, we don't
488 // need to do so again.
489 //
490 // NOTE: That we just drop these paths on the ground makes caching
491 // behavior sporadic. e.g. given a diamond:
492 // A
493 // B C
494 // D
495 //
496 // ...If we walk D, B, A, C, we'll only cache the result of phi
497 // optimization for A, B, and D; C will be skipped because it dies here.
498 // This arguably isn't the worst thing ever, since:
499 // - We generally query things in a top-down order, so if we got below D
500 // without needing cache entries for {C, MemLoc}, then chances are
501 // that those cache entries would end up ultimately unused.
502 // - We still cache things for A, so C only needs to walk up a bit.
503 // If this behavior becomes problematic, we can fix without a ton of extra
504 // work.
505 if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
506 continue;
507
508 UpwardsWalkResult Res = walkToPhiOrClobber(Node, /*StopAt=*/StopWhere);
509 if (Res.IsKnownClobber) {
510 assert(Res.Result != StopWhere || Res.FromCache);
511 // If this wasn't a cache hit, we hit a clobber when walking. That's a
512 // failure.
513 if (!Res.FromCache || !MSSA.dominates(Res.Result, StopWhere))
514 return PathIndex;
515
516 // Otherwise, it's a valid thing to potentially optimize to.
517 Terminated.push_back({Res.Result, PathIndex});
518 continue;
519 }
520
521 if (Res.Result == StopWhere) {
522 // We've hit our target. Save this path off for if we want to continue
523 // walking.
524 NewPaused.push_back(PathIndex);
525 continue;
526 }
527
528 assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
529 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
530 }
531
532 return None;
533 }
534
535 template <typename T, typename Walker>
536 struct generic_def_path_iterator
537 : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
538 std::forward_iterator_tag, T *> {
539 generic_def_path_iterator() : W(nullptr), N(None) {}
540 generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
541
542 T &operator*() const { return curNode(); }
543
544 generic_def_path_iterator &operator++() {
545 N = curNode().Previous;
546 return *this;
547 }
548
549 bool operator==(const generic_def_path_iterator &O) const {
550 if (N.hasValue() != O.N.hasValue())
551 return false;
552 return !N.hasValue() || *N == *O.N;
553 }
554
555 private:
556 T &curNode() const { return W->Paths[*N]; }
557
558 Walker *W;
559 Optional<ListIndex> N;
560 };
561
562 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
563 using const_def_path_iterator =
564 generic_def_path_iterator<const DefPath, const ClobberWalker>;
565
566 iterator_range<def_path_iterator> def_path(ListIndex From) {
567 return make_range(def_path_iterator(this, From), def_path_iterator());
568 }
569
570 iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
571 return make_range(const_def_path_iterator(this, From),
572 const_def_path_iterator());
573 }
574
575 struct OptznResult {
576 /// The path that contains our result.
577 TerminatedPath PrimaryClobber;
578 /// The paths that we can legally cache back from, but that aren't
579 /// necessarily the result of the Phi optimization.
580 SmallVector<TerminatedPath, 4> OtherClobbers;
581 };
582
583 ListIndex defPathIndex(const DefPath &N) const {
584 // The assert looks nicer if we don't need to do &N
585 const DefPath *NP = &N;
586 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
587 "Out of bounds DefPath!");
588 return NP - &Paths.front();
589 }
590
591 /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
592 /// that act as legal clobbers. Note that this won't return *all* clobbers.
593 ///
594 /// Phi optimization algorithm tl;dr:
595 /// - Find the earliest def/phi, A, we can optimize to
596 /// - Find if all paths from the starting memory access ultimately reach A
597 /// - If not, optimization isn't possible.
598 /// - Otherwise, walk from A to another clobber or phi, A'.
599 /// - If A' is a def, we're done.
600 /// - If A' is a phi, try to optimize it.
601 ///
602 /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
603 /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
604 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
605 const MemoryLocation &Loc) {
606 assert(Paths.empty() && VisitedPhis.empty() &&
607 "Reset the optimization state.");
608
609 Paths.emplace_back(Loc, Start, Phi, None);
610 // Stores how many "valid" optimization nodes we had prior to calling
611 // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
612 auto PriorPathsSize = Paths.size();
613
614 SmallVector<ListIndex, 16> PausedSearches;
615 SmallVector<ListIndex, 8> NewPaused;
616 SmallVector<TerminatedPath, 4> TerminatedPaths;
617
618 addSearches(Phi, PausedSearches, 0);
619
620 // Moves the TerminatedPath with the "most dominated" Clobber to the end of
621 // Paths.
622 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
623 assert(!Paths.empty() && "Need a path to move");
George Burgess IV5f308972016-07-19 01:29:15 +0000624 auto Dom = Paths.begin();
625 for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
626 if (!MSSA.dominates(I->Clobber, Dom->Clobber))
627 Dom = I;
628 auto Last = Paths.end() - 1;
629 if (Last != Dom)
630 std::iter_swap(Last, Dom);
631 };
632
633 MemoryPhi *Current = Phi;
634 while (1) {
635 assert(!MSSA.isLiveOnEntryDef(Current) &&
636 "liveOnEntry wasn't treated as a clobber?");
637
638 MemoryAccess *Target = getWalkTarget(Current);
639 // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
640 // optimization for the prior phi.
641 assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
642 return MSSA.dominates(P.Clobber, Target);
643 }));
644
645 // FIXME: This is broken, because the Blocker may be reported to be
646 // liveOnEntry, and we'll happily wait for that to disappear (read: never)
647 // For the moment, this is fine, since we do basically nothing with
648 // blocker info.
649 if (Optional<ListIndex> Blocker = getBlockingAccess(
650 Target, PausedSearches, NewPaused, TerminatedPaths)) {
651 MemoryAccess *BlockingAccess = Paths[*Blocker].Last;
652 // Cache our work on the blocking node, since we know that's correct.
653 cacheDefPath(Paths[*Blocker], BlockingAccess);
654
655 // Find the node we started at. We can't search based on N->Last, since
656 // we may have gone around a loop with a different MemoryLocation.
657 auto Iter = find_if(def_path(*Blocker), [&](const DefPath &N) {
658 return defPathIndex(N) < PriorPathsSize;
659 });
660 assert(Iter != def_path_iterator());
661
662 DefPath &CurNode = *Iter;
663 assert(CurNode.Last == Current);
664 CurNode.Blocker = BlockingAccess;
665
666 // Two things:
667 // A. We can't reliably cache all of NewPaused back. Consider a case
668 // where we have two paths in NewPaused; one of which can't optimize
669 // above this phi, whereas the other can. If we cache the second path
670 // back, we'll end up with suboptimal cache entries. We can handle
671 // cases like this a bit better when we either try to find all
672 // clobbers that block phi optimization, or when our cache starts
673 // supporting unfinished searches.
674 // B. We can't reliably cache TerminatedPaths back here without doing
675 // extra checks; consider a case like:
676 // T
677 // / \
678 // D C
679 // \ /
680 // S
681 // Where T is our target, C is a node with a clobber on it, D is a
682 // diamond (with a clobber *only* on the left or right node, N), and
683 // S is our start. Say we walk to D, through the node opposite N
684 // (read: ignoring the clobber), and see a cache entry in the top
685 // node of D. That cache entry gets put into TerminatedPaths. We then
686 // walk up to C (N is later in our worklist), find the clobber, and
687 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
688 // the bottom part of D to the cached clobber, ignoring the clobber
689 // in N. Again, this problem goes away if we start tracking all
690 // blockers for a given phi optimization.
691 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
692 return {Result, {}};
693 }
694
695 // If there's nothing left to search, then all paths led to valid clobbers
696 // that we got from our cache; pick the nearest to the start, and allow
697 // the rest to be cached back.
698 if (NewPaused.empty()) {
699 MoveDominatedPathToEnd(TerminatedPaths);
700 TerminatedPath Result = TerminatedPaths.pop_back_val();
701 return {Result, std::move(TerminatedPaths)};
702 }
703
704 MemoryAccess *DefChainEnd = nullptr;
705 SmallVector<TerminatedPath, 4> Clobbers;
706 for (ListIndex Paused : NewPaused) {
707 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
708 if (WR.IsKnownClobber)
709 Clobbers.push_back({WR.Result, Paused});
710 else
711 // Micro-opt: If we hit the end of the chain, save it.
712 DefChainEnd = WR.Result;
713 }
714
715 if (!TerminatedPaths.empty()) {
716 // If we couldn't find the dominating phi/liveOnEntry in the above loop,
717 // do it now.
718 if (!DefChainEnd)
719 for (MemoryAccess *MA : def_chain(Target))
720 DefChainEnd = MA;
721
722 // If any of the terminated paths don't dominate the phi we'll try to
723 // optimize, we need to figure out what they are and quit.
724 const BasicBlock *ChainBB = DefChainEnd->getBlock();
725 for (const TerminatedPath &TP : TerminatedPaths) {
726 // Because we know that DefChainEnd is as "high" as we can go, we
727 // don't need local dominance checks; BB dominance is sufficient.
728 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
729 Clobbers.push_back(TP);
730 }
731 }
732
733 // If we have clobbers in the def chain, find the one closest to Current
734 // and quit.
735 if (!Clobbers.empty()) {
736 MoveDominatedPathToEnd(Clobbers);
737 TerminatedPath Result = Clobbers.pop_back_val();
738 return {Result, std::move(Clobbers)};
739 }
740
741 assert(all_of(NewPaused,
742 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
743
744 // Because liveOnEntry is a clobber, this must be a phi.
745 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
746
747 PriorPathsSize = Paths.size();
748 PausedSearches.clear();
749 for (ListIndex I : NewPaused)
750 addSearches(DefChainPhi, PausedSearches, I);
751 NewPaused.clear();
752
753 Current = DefChainPhi;
754 }
755 }
756
757 /// Caches everything in an OptznResult.
758 void cacheOptResult(const OptznResult &R) {
759 if (R.OtherClobbers.empty()) {
760 // If we're not going to be caching OtherClobbers, don't bother with
761 // marking visited/etc.
762 for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode))
763 cacheDefPath(N, R.PrimaryClobber.Clobber);
764 return;
765 }
766
767 // PrimaryClobber is our answer. If we can cache anything back, we need to
768 // stop caching when we visit PrimaryClobber.
769 SmallBitVector Visited(Paths.size());
770 for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode)) {
771 Visited[defPathIndex(N)] = true;
772 cacheDefPath(N, R.PrimaryClobber.Clobber);
773 }
774
775 for (const TerminatedPath &P : R.OtherClobbers) {
776 for (const DefPath &N : const_def_path(P.LastNode)) {
777 ListIndex NIndex = defPathIndex(N);
778 if (Visited[NIndex])
779 break;
780 Visited[NIndex] = true;
781 cacheDefPath(N, P.Clobber);
782 }
783 }
784 }
785
786 void verifyOptResult(const OptznResult &R) const {
787 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
788 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
789 }));
790 }
791
792 void resetPhiOptznState() {
793 Paths.clear();
794 VisitedPhis.clear();
795 }
796
797public:
798 ClobberWalker(const MemorySSA &MSSA, AliasAnalysis &AA, DominatorTree &DT,
799 WalkerCache &WC)
800 : MSSA(MSSA), AA(AA), DT(DT), WC(WC), UseCache(true) {}
801
802 void reset() { WalkTargetCache.clear(); }
803
804 /// Finds the nearest clobber for the given query, optimizing phis if
805 /// possible.
806 MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q,
807 bool UseWalkerCache = true) {
808 setUseCache(UseWalkerCache);
809 Query = &Q;
810
811 MemoryAccess *Current = Start;
812 // This walker pretends uses don't exist. If we're handed one, silently grab
813 // its def. (This has the nice side-effect of ensuring we never cache uses)
814 if (auto *MU = dyn_cast<MemoryUse>(Start))
815 Current = MU->getDefiningAccess();
816
817 DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
818 // Fast path for the overly-common case (no crazy phi optimization
819 // necessary)
820 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
821 if (WalkResult.IsKnownClobber) {
822 cacheDefPath(FirstDesc, WalkResult.Result);
823 return WalkResult.Result;
824 }
825
826 OptznResult OptRes =
827 tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last), Current, Q.StartingLoc);
828 verifyOptResult(OptRes);
829 cacheOptResult(OptRes);
830 resetPhiOptznState();
831
832#ifdef EXPENSIVE_CHECKS
833 checkClobberSanity(Current, OptRes.PrimaryClobber.Clobber, Q.StartingLoc,
834 MSSA, Q, AA);
835#endif
836 return OptRes.PrimaryClobber.Clobber;
837 }
838};
839
840struct RenamePassData {
841 DomTreeNode *DTN;
842 DomTreeNode::const_iterator ChildIt;
843 MemoryAccess *IncomingVal;
844
845 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
846 MemoryAccess *M)
847 : DTN(D), ChildIt(It), IncomingVal(M) {}
848 void swap(RenamePassData &RHS) {
849 std::swap(DTN, RHS.DTN);
850 std::swap(ChildIt, RHS.ChildIt);
851 std::swap(IncomingVal, RHS.IncomingVal);
852 }
853};
854} // anonymous namespace
855
856namespace llvm {
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000857/// \brief A MemorySSAWalker that does AA walks and caching of lookups to
858/// disambiguate accesses.
859///
860/// FIXME: The current implementation of this can take quadratic space in rare
861/// cases. This can be fixed, but it is something to note until it is fixed.
862///
863/// In order to trigger this behavior, you need to store to N distinct locations
864/// (that AA can prove don't alias), perform M stores to other memory
865/// locations that AA can prove don't alias any of the initial N locations, and
866/// then load from all of the N locations. In this case, we insert M cache
867/// entries for each of the N loads.
868///
869/// For example:
870/// define i32 @foo() {
871/// %a = alloca i32, align 4
872/// %b = alloca i32, align 4
873/// store i32 0, i32* %a, align 4
874/// store i32 0, i32* %b, align 4
875///
876/// ; Insert M stores to other memory that doesn't alias %a or %b here
877///
878/// %c = load i32, i32* %a, align 4 ; Caches M entries in
879/// ; CachedUpwardsClobberingAccess for the
880/// ; MemoryLocation %a
881/// %d = load i32, i32* %b, align 4 ; Caches M entries in
882/// ; CachedUpwardsClobberingAccess for the
883/// ; MemoryLocation %b
884///
885/// ; For completeness' sake, loading %a or %b again would not cache *another*
886/// ; M entries.
887/// %r = add i32 %c, %d
888/// ret i32 %r
889/// }
890class MemorySSA::CachingWalker final : public MemorySSAWalker {
George Burgess IV5f308972016-07-19 01:29:15 +0000891 WalkerCache Cache;
892 ClobberWalker Walker;
893 bool AutoResetWalker;
894
895 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, UpwardsMemoryQuery &);
896 void verifyRemoved(MemoryAccess *);
897
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000898public:
899 CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *);
900 ~CachingWalker() override;
901
George Burgess IV400ae402016-07-20 19:51:34 +0000902 using MemorySSAWalker::getClobberingMemoryAccess;
903 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override;
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000904 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
905 MemoryLocation &) override;
906 void invalidateInfo(MemoryAccess *) override;
907
George Burgess IV5f308972016-07-19 01:29:15 +0000908 /// Whether we call resetClobberWalker() after each time we *actually* walk to
909 /// answer a clobber query.
910 void setAutoResetWalker(bool AutoReset) { AutoResetWalker = AutoReset; }
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000911
George Burgess IV5f308972016-07-19 01:29:15 +0000912 /// Drop the walker's persistent data structures. At the moment, this means
913 /// "drop the walker's cache of BasicBlocks ->
914 /// earliest-MemoryAccess-we-can-optimize-to". This is necessary if we're
915 /// going to have DT updates, if we remove MemoryAccesses, etc.
916 void resetClobberWalker() { Walker.reset(); }
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000917};
George Burgess IVe1100f52016-02-02 22:46:49 +0000918
George Burgess IVe1100f52016-02-02 22:46:49 +0000919/// \brief Rename a single basic block into MemorySSA form.
920/// Uses the standard SSA renaming algorithm.
921/// \returns The new incoming value.
922MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB,
923 MemoryAccess *IncomingVal) {
924 auto It = PerBlockAccesses.find(BB);
925 // Skip most processing if the list is empty.
926 if (It != PerBlockAccesses.end()) {
Daniel Berlinada263d2016-06-20 20:21:33 +0000927 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000928 for (MemoryAccess &L : *Accesses) {
929 switch (L.getValueID()) {
930 case Value::MemoryUseVal:
931 cast<MemoryUse>(&L)->setDefiningAccess(IncomingVal);
932 break;
933 case Value::MemoryDefVal:
934 // We can't legally optimize defs, because we only allow single
935 // memory phis/uses on operations, and if we optimize these, we can
936 // end up with multiple reaching defs. Uses do not have this
937 // problem, since they do not produce a value
938 cast<MemoryDef>(&L)->setDefiningAccess(IncomingVal);
939 IncomingVal = &L;
940 break;
941 case Value::MemoryPhiVal:
942 IncomingVal = &L;
943 break;
944 }
945 }
946 }
947
948 // Pass through values to our successors
949 for (const BasicBlock *S : successors(BB)) {
950 auto It = PerBlockAccesses.find(S);
951 // Rename the phi nodes in our successor block
952 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
953 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +0000954 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000955 auto *Phi = cast<MemoryPhi>(&Accesses->front());
George Burgess IVe1100f52016-02-02 22:46:49 +0000956 Phi->addIncoming(IncomingVal, BB);
957 }
958
959 return IncomingVal;
960}
961
962/// \brief This is the standard SSA renaming algorithm.
963///
964/// We walk the dominator tree in preorder, renaming accesses, and then filling
965/// in phi nodes in our successors.
966void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
967 SmallPtrSet<BasicBlock *, 16> &Visited) {
968 SmallVector<RenamePassData, 32> WorkStack;
969 IncomingVal = renameBlock(Root->getBlock(), IncomingVal);
970 WorkStack.push_back({Root, Root->begin(), IncomingVal});
971 Visited.insert(Root->getBlock());
972
973 while (!WorkStack.empty()) {
974 DomTreeNode *Node = WorkStack.back().DTN;
975 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
976 IncomingVal = WorkStack.back().IncomingVal;
977
978 if (ChildIt == Node->end()) {
979 WorkStack.pop_back();
980 } else {
981 DomTreeNode *Child = *ChildIt;
982 ++WorkStack.back().ChildIt;
983 BasicBlock *BB = Child->getBlock();
984 Visited.insert(BB);
985 IncomingVal = renameBlock(BB, IncomingVal);
986 WorkStack.push_back({Child, Child->begin(), IncomingVal});
987 }
988 }
989}
990
991/// \brief Compute dominator levels, used by the phi insertion algorithm above.
992void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) {
993 for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode());
994 DFI != DFE; ++DFI)
995 DomLevels[*DFI] = DFI.getPathLength() - 1;
996}
997
George Burgess IVa362b092016-07-06 00:28:43 +0000998/// \brief This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +0000999/// unreachable blocks, and marking all other unreachable MemoryAccess's as
1000/// being uses of the live on entry definition.
1001void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
1002 assert(!DT->isReachableFromEntry(BB) &&
1003 "Reachable block found while handling unreachable blocks");
1004
Daniel Berlinfc7e6512016-07-06 05:32:05 +00001005 // Make sure phi nodes in our reachable successors end up with a
1006 // LiveOnEntryDef for our incoming edge, even though our block is forward
1007 // unreachable. We could just disconnect these blocks from the CFG fully,
1008 // but we do not right now.
1009 for (const BasicBlock *S : successors(BB)) {
1010 if (!DT->isReachableFromEntry(S))
1011 continue;
1012 auto It = PerBlockAccesses.find(S);
1013 // Rename the phi nodes in our successor block
1014 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1015 continue;
1016 AccessList *Accesses = It->second.get();
1017 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1018 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1019 }
1020
George Burgess IVe1100f52016-02-02 22:46:49 +00001021 auto It = PerBlockAccesses.find(BB);
1022 if (It == PerBlockAccesses.end())
1023 return;
1024
1025 auto &Accesses = It->second;
1026 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1027 auto Next = std::next(AI);
1028 // If we have a phi, just remove it. We are going to replace all
1029 // users with live on entry.
1030 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1031 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1032 else
1033 Accesses->erase(AI);
1034 AI = Next;
1035 }
1036}
1037
Geoff Berryb96d3b22016-06-01 21:30:40 +00001038MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
1039 : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
1040 NextID(0) {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001041 buildMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001042}
1043
1044MemorySSA::MemorySSA(MemorySSA &&MSSA)
1045 : AA(MSSA.AA), DT(MSSA.DT), F(MSSA.F),
1046 ValueToMemoryAccess(std::move(MSSA.ValueToMemoryAccess)),
1047 PerBlockAccesses(std::move(MSSA.PerBlockAccesses)),
1048 LiveOnEntryDef(std::move(MSSA.LiveOnEntryDef)),
1049 Walker(std::move(MSSA.Walker)), NextID(MSSA.NextID) {
1050 // Update the Walker MSSA pointer so it doesn't point to the moved-from MSSA
1051 // object any more.
1052 Walker->MSSA = this;
1053}
George Burgess IVe1100f52016-02-02 22:46:49 +00001054
1055MemorySSA::~MemorySSA() {
1056 // Drop all our references
1057 for (const auto &Pair : PerBlockAccesses)
1058 for (MemoryAccess &MA : *Pair.second)
1059 MA.dropAllReferences();
1060}
1061
Daniel Berlin14300262016-06-21 18:39:20 +00001062MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001063 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1064
1065 if (Res.second)
Daniel Berlinada263d2016-06-20 20:21:33 +00001066 Res.first->second = make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001067 return Res.first->second.get();
1068}
1069
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001070void MemorySSA::buildMemorySSA() {
George Burgess IVe1100f52016-02-02 22:46:49 +00001071 // We create an access to represent "live on entry", for things like
1072 // arguments or users of globals, where the memory they use is defined before
1073 // the beginning of the function. We do not actually insert it into the IR.
1074 // We do not define a live on exit for the immediate uses, and thus our
1075 // semantics do *not* imply that something with no immediate uses can simply
1076 // be removed.
1077 BasicBlock &StartingPoint = F.getEntryBlock();
1078 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
1079 &StartingPoint, NextID++);
1080
1081 // We maintain lists of memory accesses per-block, trading memory for time. We
1082 // could just look up the memory access for every possible instruction in the
1083 // stream.
1084 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001085 SmallPtrSet<BasicBlock *, 32> DefUseBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001086 // Go through each block, figure out where defs occur, and chain together all
1087 // the accesses.
1088 for (BasicBlock &B : F) {
Daniel Berlin7898ca62016-02-07 01:52:15 +00001089 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001090 AccessList *Accesses = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001091 for (Instruction &I : B) {
Peter Collingbourneffecb142016-05-26 01:19:17 +00001092 MemoryUseOrDef *MUD = createNewAccess(&I);
George Burgess IVb42b7622016-03-11 19:34:03 +00001093 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001094 continue;
George Burgess IV3887a412016-03-21 21:25:39 +00001095 InsertIntoDef |= isa<MemoryDef>(MUD);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001096
George Burgess IVe1100f52016-02-02 22:46:49 +00001097 if (!Accesses)
1098 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001099 Accesses->push_back(MUD);
George Burgess IVe1100f52016-02-02 22:46:49 +00001100 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001101 if (InsertIntoDef)
1102 DefiningBlocks.insert(&B);
George Burgess IV3887a412016-03-21 21:25:39 +00001103 if (Accesses)
Daniel Berlin1b51a292016-02-07 01:52:19 +00001104 DefUseBlocks.insert(&B);
1105 }
1106
1107 // Compute live-in.
1108 // Live in is normally defined as "all the blocks on the path from each def to
1109 // each of it's uses".
1110 // MemoryDef's are implicit uses of previous state, so they are also uses.
1111 // This means we don't really have def-only instructions. The only
1112 // MemoryDef's that are not really uses are those that are of the LiveOnEntry
1113 // variable (because LiveOnEntry can reach anywhere, and every def is a
1114 // must-kill of LiveOnEntry).
1115 // In theory, you could precisely compute live-in by using alias-analysis to
1116 // disambiguate defs and uses to see which really pair up with which.
1117 // In practice, this would be really expensive and difficult. So we simply
1118 // assume all defs are also uses that need to be kept live.
1119 // Because of this, the end result of this live-in computation will be "the
1120 // entire set of basic blocks that reach any use".
1121
1122 SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
1123 SmallVector<BasicBlock *, 64> LiveInBlockWorklist(DefUseBlocks.begin(),
1124 DefUseBlocks.end());
1125 // Now that we have a set of blocks where a value is live-in, recursively add
1126 // predecessors until we find the full region the value is live.
1127 while (!LiveInBlockWorklist.empty()) {
1128 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
1129
1130 // The block really is live in here, insert it into the set. If already in
1131 // the set, then it has already been processed.
1132 if (!LiveInBlocks.insert(BB).second)
1133 continue;
1134
1135 // Since the value is live into BB, it is either defined in a predecessor or
1136 // live into it to.
1137 LiveInBlockWorklist.append(pred_begin(BB), pred_end(BB));
George Burgess IVe1100f52016-02-02 22:46:49 +00001138 }
1139
1140 // Determine where our MemoryPhi's should go
Daniel Berlin77fa84e2016-04-19 06:13:28 +00001141 ForwardIDFCalculator IDFs(*DT);
George Burgess IVe1100f52016-02-02 22:46:49 +00001142 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001143 IDFs.setLiveInBlocks(LiveInBlocks);
George Burgess IVe1100f52016-02-02 22:46:49 +00001144 SmallVector<BasicBlock *, 32> IDFBlocks;
1145 IDFs.calculate(IDFBlocks);
1146
1147 // Now place MemoryPhi nodes.
1148 for (auto &BB : IDFBlocks) {
1149 // Insert phi node
Daniel Berlinada263d2016-06-20 20:21:33 +00001150 AccessList *Accesses = getOrCreateAccessList(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001151 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlinf6c9ae92016-02-10 17:41:25 +00001152 ValueToMemoryAccess.insert(std::make_pair(BB, Phi));
George Burgess IVe1100f52016-02-02 22:46:49 +00001153 // Phi's always are placed at the front of the block.
1154 Accesses->push_front(Phi);
1155 }
1156
1157 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1158 // filled in with all blocks.
1159 SmallPtrSet<BasicBlock *, 16> Visited;
1160 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1161
George Burgess IV5f308972016-07-19 01:29:15 +00001162 CachingWalker *Walker = getWalkerImpl();
1163
1164 // We're doing a batch of updates; don't drop useful caches between them.
1165 Walker->setAutoResetWalker(false);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001166
George Burgess IVe1100f52016-02-02 22:46:49 +00001167 // Now optimize the MemoryUse's defining access to point to the nearest
1168 // dominating clobbering def.
1169 // This ensures that MemoryUse's that are killed by the same store are
1170 // immediate users of that store, one of the invariants we guarantee.
1171 for (auto DomNode : depth_first(DT)) {
1172 BasicBlock *BB = DomNode->getBlock();
1173 auto AI = PerBlockAccesses.find(BB);
1174 if (AI == PerBlockAccesses.end())
1175 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +00001176 AccessList *Accesses = AI->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001177 for (auto &MA : *Accesses) {
1178 if (auto *MU = dyn_cast<MemoryUse>(&MA)) {
1179 Instruction *Inst = MU->getMemoryInst();
Daniel Berlin64120022016-03-02 21:16:28 +00001180 MU->setDefiningAccess(Walker->getClobberingMemoryAccess(Inst));
George Burgess IVe1100f52016-02-02 22:46:49 +00001181 }
1182 }
1183 }
1184
George Burgess IV5f308972016-07-19 01:29:15 +00001185 Walker->setAutoResetWalker(true);
1186 Walker->resetClobberWalker();
1187
George Burgess IVe1100f52016-02-02 22:46:49 +00001188 // Mark the uses in unreachable blocks as live on entry, so that they go
1189 // somewhere.
1190 for (auto &BB : F)
1191 if (!Visited.count(&BB))
1192 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001193}
George Burgess IVe1100f52016-02-02 22:46:49 +00001194
George Burgess IV5f308972016-07-19 01:29:15 +00001195MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1196
1197MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001198 if (Walker)
1199 return Walker.get();
1200
1201 Walker = make_unique<CachingWalker>(this, AA, DT);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001202 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001203}
1204
Daniel Berlin14300262016-06-21 18:39:20 +00001205MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1206 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
1207 AccessList *Accesses = getOrCreateAccessList(BB);
1208 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
1209 ValueToMemoryAccess.insert(std::make_pair(BB, Phi));
1210 // Phi's always are placed at the front of the block.
1211 Accesses->push_front(Phi);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001212 BlockNumberingValid.erase(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001213 return Phi;
1214}
1215
1216MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
1217 MemoryAccess *Definition) {
1218 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1219 MemoryUseOrDef *NewAccess = createNewAccess(I);
1220 assert(
1221 NewAccess != nullptr &&
1222 "Tried to create a memory access for a non-memory touching instruction");
1223 NewAccess->setDefiningAccess(Definition);
1224 return NewAccess;
1225}
1226
1227MemoryAccess *MemorySSA::createMemoryAccessInBB(Instruction *I,
1228 MemoryAccess *Definition,
1229 const BasicBlock *BB,
1230 InsertionPlace Point) {
1231 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1232 auto *Accesses = getOrCreateAccessList(BB);
1233 if (Point == Beginning) {
1234 // It goes after any phi nodes
1235 auto AI = std::find_if(
1236 Accesses->begin(), Accesses->end(),
1237 [](const MemoryAccess &MA) { return !isa<MemoryPhi>(MA); });
1238
1239 Accesses->insert(AI, NewAccess);
1240 } else {
1241 Accesses->push_back(NewAccess);
1242 }
Daniel Berlin5c46b942016-07-19 22:49:43 +00001243 BlockNumberingValid.erase(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001244 return NewAccess;
1245}
1246MemoryAccess *MemorySSA::createMemoryAccessBefore(Instruction *I,
1247 MemoryAccess *Definition,
1248 MemoryAccess *InsertPt) {
1249 assert(I->getParent() == InsertPt->getBlock() &&
1250 "New and old access must be in the same block");
1251 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1252 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
1253 Accesses->insert(AccessList::iterator(InsertPt), NewAccess);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001254 BlockNumberingValid.erase(InsertPt->getBlock());
Daniel Berlin14300262016-06-21 18:39:20 +00001255 return NewAccess;
1256}
1257
1258MemoryAccess *MemorySSA::createMemoryAccessAfter(Instruction *I,
1259 MemoryAccess *Definition,
1260 MemoryAccess *InsertPt) {
1261 assert(I->getParent() == InsertPt->getBlock() &&
1262 "New and old access must be in the same block");
1263 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1264 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
1265 Accesses->insertAfter(AccessList::iterator(InsertPt), NewAccess);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001266 BlockNumberingValid.erase(InsertPt->getBlock());
Daniel Berlin14300262016-06-21 18:39:20 +00001267 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");
Daniel Berlin5c46b942016-07-19 22:49:43 +00001367 BlockNumbering.erase(MA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001368 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
1369 MUD->setDefiningAccess(nullptr);
1370 // Invalidate our walker's cache if necessary
1371 if (!isa<MemoryUse>(MA))
1372 Walker->invalidateInfo(MA);
1373 // The call below to erase will destroy MA, so we can't change the order we
1374 // are doing things here
1375 Value *MemoryInst;
1376 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1377 MemoryInst = MUD->getMemoryInst();
1378 } else {
1379 MemoryInst = MA->getBlock();
1380 }
1381 ValueToMemoryAccess.erase(MemoryInst);
1382
George Burgess IVe0e6e482016-03-02 02:35:04 +00001383 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
Daniel Berlinada263d2016-06-20 20:21:33 +00001384 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001385 Accesses->erase(MA);
George Burgess IVe0e6e482016-03-02 02:35:04 +00001386 if (Accesses->empty())
1387 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001388}
1389
1390void MemorySSA::removeMemoryAccess(MemoryAccess *MA) {
1391 assert(!isLiveOnEntryDef(MA) && "Trying to remove the live on entry def");
1392 // We can only delete phi nodes if they have no uses, or we can replace all
1393 // uses with a single definition.
1394 MemoryAccess *NewDefTarget = nullptr;
1395 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) {
1396 // Note that it is sufficient to know that all edges of the phi node have
1397 // the same argument. If they do, by the definition of dominance frontiers
1398 // (which we used to place this phi), that argument must dominate this phi,
1399 // and thus, must dominate the phi's uses, and so we will not hit the assert
1400 // below.
1401 NewDefTarget = onlySingleValue(MP);
1402 assert((NewDefTarget || MP->use_empty()) &&
1403 "We can't delete this memory phi");
1404 } else {
1405 NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
1406 }
1407
1408 // Re-point the uses at our defining access
1409 if (!MA->use_empty())
1410 MA->replaceAllUsesWith(NewDefTarget);
1411
1412 // The call below to erase will destroy MA, so we can't change the order we
1413 // are doing things here
1414 removeFromLookups(MA);
1415}
1416
George Burgess IVe1100f52016-02-02 22:46:49 +00001417void MemorySSA::print(raw_ostream &OS) const {
1418 MemorySSAAnnotatedWriter Writer(this);
1419 F.print(OS, &Writer);
1420}
1421
1422void MemorySSA::dump() const {
1423 MemorySSAAnnotatedWriter Writer(this);
1424 F.print(dbgs(), &Writer);
1425}
1426
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001427void MemorySSA::verifyMemorySSA() const {
1428 verifyDefUses(F);
1429 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001430 verifyOrdering(F);
1431}
1432
1433/// \brief Verify that the order and existence of MemoryAccesses matches the
1434/// order and existence of memory affecting instructions.
1435void MemorySSA::verifyOrdering(Function &F) const {
1436 // Walk all the blocks, comparing what the lookups think and what the access
1437 // lists think, as well as the order in the blocks vs the order in the access
1438 // lists.
1439 SmallVector<MemoryAccess *, 32> ActualAccesses;
1440 for (BasicBlock &B : F) {
1441 const AccessList *AL = getBlockAccesses(&B);
1442 MemoryAccess *Phi = getMemoryAccess(&B);
1443 if (Phi)
1444 ActualAccesses.push_back(Phi);
1445 for (Instruction &I : B) {
1446 MemoryAccess *MA = getMemoryAccess(&I);
1447 assert((!MA || AL) && "We have memory affecting instructions "
1448 "in this block but they are not in the "
1449 "access list");
1450 if (MA)
1451 ActualAccesses.push_back(MA);
1452 }
1453 // Either we hit the assert, really have no accesses, or we have both
1454 // accesses and an access list
1455 if (!AL)
1456 continue;
1457 assert(AL->size() == ActualAccesses.size() &&
1458 "We don't have the same number of accesses in the block as on the "
1459 "access list");
1460 auto ALI = AL->begin();
1461 auto AAI = ActualAccesses.begin();
1462 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1463 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1464 ++ALI;
1465 ++AAI;
1466 }
1467 ActualAccesses.clear();
1468 }
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001469}
1470
George Burgess IVe1100f52016-02-02 22:46:49 +00001471/// \brief Verify the domination properties of MemorySSA by checking that each
1472/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001473void MemorySSA::verifyDomination(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001474 for (BasicBlock &B : F) {
1475 // Phi nodes are attached to basic blocks
1476 if (MemoryPhi *MP = getMemoryAccess(&B)) {
1477 for (User *U : MP->users()) {
1478 BasicBlock *UseBlock;
1479 // Phi operands are used on edges, we simulate the right domination by
1480 // acting as if the use occurred at the end of the predecessor block.
1481 if (MemoryPhi *P = dyn_cast<MemoryPhi>(U)) {
1482 for (const auto &Arg : P->operands()) {
1483 if (Arg == MP) {
1484 UseBlock = P->getIncomingBlock(Arg);
1485 break;
1486 }
1487 }
1488 } else {
1489 UseBlock = cast<MemoryAccess>(U)->getBlock();
1490 }
George Burgess IV60adac42016-02-02 23:26:01 +00001491 (void)UseBlock;
George Burgess IVe1100f52016-02-02 22:46:49 +00001492 assert(DT->dominates(MP->getBlock(), UseBlock) &&
1493 "Memory PHI does not dominate it's uses");
1494 }
1495 }
1496
1497 for (Instruction &I : B) {
1498 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
1499 if (!MD)
1500 continue;
1501
Benjamin Kramer451f54c2016-02-22 13:11:58 +00001502 for (User *U : MD->users()) {
Daniel Berlinada263d2016-06-20 20:21:33 +00001503 BasicBlock *UseBlock;
1504 (void)UseBlock;
George Burgess IVe1100f52016-02-02 22:46:49 +00001505 // Things are allowed to flow to phi nodes over their predecessor edge.
1506 if (auto *P = dyn_cast<MemoryPhi>(U)) {
1507 for (const auto &Arg : P->operands()) {
1508 if (Arg == MD) {
1509 UseBlock = P->getIncomingBlock(Arg);
1510 break;
1511 }
1512 }
1513 } else {
1514 UseBlock = cast<MemoryAccess>(U)->getBlock();
1515 }
1516 assert(DT->dominates(MD->getBlock(), UseBlock) &&
1517 "Memory Def does not dominate it's uses");
1518 }
1519 }
1520 }
1521}
1522
1523/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
1524/// appears in the use list of \p Def.
1525///
1526/// llvm_unreachable is used instead of asserts because this may be called in
1527/// a build without asserts. In that case, we don't want this to turn into a
1528/// nop.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001529void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001530 // The live on entry use may cause us to get a NULL def here
1531 if (!Def) {
1532 if (!isLiveOnEntryDef(Use))
1533 llvm_unreachable("Null def but use not point to live on entry def");
1534 } else if (std::find(Def->user_begin(), Def->user_end(), Use) ==
1535 Def->user_end()) {
1536 llvm_unreachable("Did not find use in def's use list");
1537 }
1538}
1539
1540/// \brief Verify the immediate use information, by walking all the memory
1541/// accesses and verifying that, for each use, it appears in the
1542/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001543void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001544 for (BasicBlock &B : F) {
1545 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00001546 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00001547 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
1548 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00001549 "Incomplete MemoryPhi Node");
George Burgess IVe1100f52016-02-02 22:46:49 +00001550 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1551 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Daniel Berlin14300262016-06-21 18:39:20 +00001552 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001553
1554 for (Instruction &I : B) {
1555 if (MemoryAccess *MA = getMemoryAccess(&I)) {
1556 assert(isa<MemoryUseOrDef>(MA) &&
1557 "Found a phi node not attached to a bb");
1558 verifyUseInDefs(cast<MemoryUseOrDef>(MA)->getDefiningAccess(), MA);
1559 }
1560 }
1561 }
1562}
1563
1564MemoryAccess *MemorySSA::getMemoryAccess(const Value *I) const {
Daniel Berlinf6c9ae92016-02-10 17:41:25 +00001565 return ValueToMemoryAccess.lookup(I);
George Burgess IVe1100f52016-02-02 22:46:49 +00001566}
1567
1568MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
1569 return cast_or_null<MemoryPhi>(getMemoryAccess((const Value *)BB));
1570}
1571
Daniel Berlin5c46b942016-07-19 22:49:43 +00001572/// Perform a local numbering on blocks so that instruction ordering can be
1573/// determined in constant time.
1574/// TODO: We currently just number in order. If we numbered by N, we could
1575/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
1576/// log2(N) sequences of mixed before and after) without needing to invalidate
1577/// the numbering.
1578void MemorySSA::renumberBlock(const BasicBlock *B) const {
1579 // The pre-increment ensures the numbers really start at 1.
1580 unsigned long CurrentNumber = 0;
1581 const AccessList *AL = getBlockAccesses(B);
1582 assert(AL != nullptr && "Asking to renumber an empty block");
1583 for (const auto &I : *AL)
1584 BlockNumbering[&I] = ++CurrentNumber;
1585 BlockNumberingValid.insert(B);
1586}
1587
George Burgess IVe1100f52016-02-02 22:46:49 +00001588/// \brief Determine, for two memory accesses in the same block,
1589/// whether \p Dominator dominates \p Dominatee.
1590/// \returns True if \p Dominator dominates \p Dominatee.
1591bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
1592 const MemoryAccess *Dominatee) const {
Sebastian Pope1f60b12016-06-10 21:36:41 +00001593
Daniel Berlin5c46b942016-07-19 22:49:43 +00001594 const BasicBlock *DominatorBlock = Dominator->getBlock();
Daniel Berlin5c46b942016-07-19 22:49:43 +00001595
Daniel Berlin19860302016-07-19 23:08:08 +00001596 assert((DominatorBlock == Dominatee->getBlock()) &&
Daniel Berlin5c46b942016-07-19 22:49:43 +00001597 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00001598 // A node dominates itself.
1599 if (Dominatee == Dominator)
1600 return true;
1601
1602 // When Dominatee is defined on function entry, it is not dominated by another
1603 // memory access.
1604 if (isLiveOnEntryDef(Dominatee))
1605 return false;
1606
1607 // When Dominator is defined on function entry, it dominates the other memory
1608 // access.
1609 if (isLiveOnEntryDef(Dominator))
1610 return true;
1611
Daniel Berlin5c46b942016-07-19 22:49:43 +00001612 if (!BlockNumberingValid.count(DominatorBlock))
1613 renumberBlock(DominatorBlock);
George Burgess IVe1100f52016-02-02 22:46:49 +00001614
Daniel Berlin5c46b942016-07-19 22:49:43 +00001615 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
1616 // All numbers start with 1
1617 assert(DominatorNum != 0 && "Block was not numbered properly");
1618 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
1619 assert(DominateeNum != 0 && "Block was not numbered properly");
1620 return DominatorNum < DominateeNum;
George Burgess IVe1100f52016-02-02 22:46:49 +00001621}
1622
George Burgess IV5f308972016-07-19 01:29:15 +00001623bool MemorySSA::dominates(const MemoryAccess *Dominator,
1624 const MemoryAccess *Dominatee) const {
1625 if (Dominator == Dominatee)
1626 return true;
1627
1628 if (isLiveOnEntryDef(Dominatee))
1629 return false;
1630
1631 if (Dominator->getBlock() != Dominatee->getBlock())
1632 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
1633 return locallyDominates(Dominator, Dominatee);
1634}
1635
George Burgess IVe1100f52016-02-02 22:46:49 +00001636const static char LiveOnEntryStr[] = "liveOnEntry";
1637
1638void MemoryDef::print(raw_ostream &OS) const {
1639 MemoryAccess *UO = getDefiningAccess();
1640
1641 OS << getID() << " = MemoryDef(";
1642 if (UO && UO->getID())
1643 OS << UO->getID();
1644 else
1645 OS << LiveOnEntryStr;
1646 OS << ')';
1647}
1648
1649void MemoryPhi::print(raw_ostream &OS) const {
1650 bool First = true;
1651 OS << getID() << " = MemoryPhi(";
1652 for (const auto &Op : operands()) {
1653 BasicBlock *BB = getIncomingBlock(Op);
1654 MemoryAccess *MA = cast<MemoryAccess>(Op);
1655 if (!First)
1656 OS << ',';
1657 else
1658 First = false;
1659
1660 OS << '{';
1661 if (BB->hasName())
1662 OS << BB->getName();
1663 else
1664 BB->printAsOperand(OS, false);
1665 OS << ',';
1666 if (unsigned ID = MA->getID())
1667 OS << ID;
1668 else
1669 OS << LiveOnEntryStr;
1670 OS << '}';
1671 }
1672 OS << ')';
1673}
1674
1675MemoryAccess::~MemoryAccess() {}
1676
1677void MemoryUse::print(raw_ostream &OS) const {
1678 MemoryAccess *UO = getDefiningAccess();
1679 OS << "MemoryUse(";
1680 if (UO && UO->getID())
1681 OS << UO->getID();
1682 else
1683 OS << LiveOnEntryStr;
1684 OS << ')';
1685}
1686
1687void MemoryAccess::dump() const {
1688 print(dbgs());
1689 dbgs() << "\n";
1690}
1691
Chad Rosier232e29e2016-07-06 21:20:47 +00001692char MemorySSAPrinterLegacyPass::ID = 0;
1693
1694MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
1695 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
1696}
1697
1698void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
1699 AU.setPreservesAll();
1700 AU.addRequired<MemorySSAWrapperPass>();
1701 AU.addPreserved<MemorySSAWrapperPass>();
1702}
1703
1704bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
1705 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
1706 MSSA.print(dbgs());
1707 if (VerifyMemorySSA)
1708 MSSA.verifyMemorySSA();
1709 return false;
1710}
1711
Geoff Berryb96d3b22016-06-01 21:30:40 +00001712char MemorySSAAnalysis::PassID;
George Burgess IVe1100f52016-02-02 22:46:49 +00001713
Geoff Berryb96d3b22016-06-01 21:30:40 +00001714MemorySSA MemorySSAAnalysis::run(Function &F, AnalysisManager<Function> &AM) {
1715 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1716 auto &AA = AM.getResult<AAManager>(F);
1717 return MemorySSA(F, &AA, &DT);
George Burgess IVe1100f52016-02-02 22:46:49 +00001718}
1719
Geoff Berryb96d3b22016-06-01 21:30:40 +00001720PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
1721 FunctionAnalysisManager &AM) {
1722 OS << "MemorySSA for function: " << F.getName() << "\n";
1723 AM.getResult<MemorySSAAnalysis>(F).print(OS);
1724
1725 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00001726}
1727
Geoff Berryb96d3b22016-06-01 21:30:40 +00001728PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
1729 FunctionAnalysisManager &AM) {
1730 AM.getResult<MemorySSAAnalysis>(F).verifyMemorySSA();
1731
1732 return PreservedAnalyses::all();
1733}
1734
1735char MemorySSAWrapperPass::ID = 0;
1736
1737MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
1738 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
1739}
1740
1741void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
1742
1743void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001744 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001745 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
1746 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001747}
1748
Geoff Berryb96d3b22016-06-01 21:30:40 +00001749bool MemorySSAWrapperPass::runOnFunction(Function &F) {
1750 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1751 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1752 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00001753 return false;
1754}
1755
Geoff Berryb96d3b22016-06-01 21:30:40 +00001756void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00001757
Geoff Berryb96d3b22016-06-01 21:30:40 +00001758void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001759 MSSA->print(OS);
1760}
1761
George Burgess IVe1100f52016-02-02 22:46:49 +00001762MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
1763
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001764MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A,
1765 DominatorTree *D)
Daniel Berlin5c46b942016-07-19 22:49:43 +00001766 : MemorySSAWalker(M), Walker(*M, *A, *D, Cache), AutoResetWalker(true) {}
George Burgess IVe1100f52016-02-02 22:46:49 +00001767
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001768MemorySSA::CachingWalker::~CachingWalker() {}
George Burgess IVe1100f52016-02-02 22:46:49 +00001769
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001770void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) {
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001771 // TODO: We can do much better cache invalidation with differently stored
1772 // caches. For now, for MemoryUses, we simply remove them
1773 // from the cache, and kill the entire call/non-call cache for everything
1774 // else. The problem is for phis or defs, currently we'd need to follow use
1775 // chains down and invalidate anything below us in the chain that currently
1776 // terminates at this access.
1777
1778 // See if this is a MemoryUse, if so, just remove the cached info. MemoryUse
1779 // is by definition never a barrier, so nothing in the cache could point to
1780 // this use. In that case, we only need invalidate the info for the use
1781 // itself.
1782
1783 if (MemoryUse *MU = dyn_cast<MemoryUse>(MA)) {
George Burgess IV5f308972016-07-19 01:29:15 +00001784 UpwardsMemoryQuery Q(MU->getMemoryInst(), MU);
1785 Cache.remove(MU, Q.StartingLoc, Q.IsCall);
Geoff Berry9fe26e62016-04-22 14:44:10 +00001786 } else {
1787 // 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 +00001788 Cache.clear();
Geoff Berry9fe26e62016-04-22 14:44:10 +00001789 }
1790
Filipe Cabecinhas0da99372016-04-29 15:22:48 +00001791#ifdef EXPENSIVE_CHECKS
Geoff Berry9fe26e62016-04-22 14:44:10 +00001792 verifyRemoved(MA);
1793#endif
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001794}
1795
George Burgess IVe1100f52016-02-02 22:46:49 +00001796/// \brief Walk the use-def chains starting at \p MA and find
1797/// the MemoryAccess that actually clobbers Loc.
1798///
1799/// \returns our clobbering memory access
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001800MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
1801 MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +00001802 MemoryAccess *New = Walker.findClobber(StartingAccess, Q);
1803#ifdef EXPENSIVE_CHECKS
1804 MemoryAccess *NewNoCache =
1805 Walker.findClobber(StartingAccess, Q, /*UseWalkerCache=*/false);
1806 assert(NewNoCache == New && "Cache made us hand back a different result?");
1807#endif
1808 if (AutoResetWalker)
1809 resetClobberWalker();
1810 return New;
George Burgess IVe1100f52016-02-02 22:46:49 +00001811}
1812
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001813MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
1814 MemoryAccess *StartingAccess, MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001815 if (isa<MemoryPhi>(StartingAccess))
1816 return StartingAccess;
1817
1818 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
1819 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
1820 return StartingUseOrDef;
1821
1822 Instruction *I = StartingUseOrDef->getMemoryInst();
1823
1824 // Conservatively, fences are always clobbers, so don't perform the walk if we
1825 // hit a fence.
David Majnemera940f362016-07-15 17:19:24 +00001826 if (!ImmutableCallSite(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00001827 return StartingUseOrDef;
1828
1829 UpwardsMemoryQuery Q;
1830 Q.OriginalAccess = StartingUseOrDef;
1831 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00001832 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00001833 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00001834
George Burgess IV5f308972016-07-19 01:29:15 +00001835 if (auto *CacheResult = Cache.lookup(StartingUseOrDef, Loc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00001836 return CacheResult;
1837
1838 // Unlike the other function, do not walk to the def of a def, because we are
1839 // handed something we already believe is the clobbering access.
1840 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
1841 ? StartingUseOrDef->getDefiningAccess()
1842 : StartingUseOrDef;
1843
1844 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00001845 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
1846 DEBUG(dbgs() << *StartingUseOrDef << "\n");
1847 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
1848 DEBUG(dbgs() << *Clobber << "\n");
1849 return Clobber;
1850}
1851
1852MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00001853MemorySSA::CachingWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
1854 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
1855 // If this is a MemoryPhi, we can't do anything.
1856 if (!StartingAccess)
1857 return MA;
George Burgess IVe1100f52016-02-02 22:46:49 +00001858
George Burgess IV400ae402016-07-20 19:51:34 +00001859 const Instruction *I = StartingAccess->getMemoryInst();
George Burgess IV5f308972016-07-19 01:29:15 +00001860 UpwardsMemoryQuery Q(I, StartingAccess);
David Majnemera940f362016-07-15 17:19:24 +00001861 // We can't sanely do anything with a fences, they conservatively
George Burgess IVe1100f52016-02-02 22:46:49 +00001862 // clobber all memory, and have no locations to get pointers from to
David Majnemera940f362016-07-15 17:19:24 +00001863 // try to disambiguate.
George Burgess IV5f308972016-07-19 01:29:15 +00001864 if (!Q.IsCall && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00001865 return StartingAccess;
1866
George Burgess IV5f308972016-07-19 01:29:15 +00001867 if (auto *CacheResult = Cache.lookup(StartingAccess, Q.StartingLoc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00001868 return CacheResult;
1869
1870 // Start with the thing we already think clobbers this location
1871 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
1872
1873 // At this point, DefiningAccess may be the live on entry def.
1874 // If it is, we will not get a better result.
1875 if (MSSA->isLiveOnEntryDef(DefiningAccess))
1876 return DefiningAccess;
1877
1878 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00001879 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
1880 DEBUG(dbgs() << *DefiningAccess << "\n");
1881 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
1882 DEBUG(dbgs() << *Result << "\n");
1883
1884 return Result;
1885}
1886
Geoff Berry9fe26e62016-04-22 14:44:10 +00001887// Verify that MA doesn't exist in any of the caches.
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001888void MemorySSA::CachingWalker::verifyRemoved(MemoryAccess *MA) {
George Burgess IV5f308972016-07-19 01:29:15 +00001889 assert(!Cache.contains(MA) && "Found removed MemoryAccess in cache.");
Geoff Berry9fe26e62016-04-22 14:44:10 +00001890}
1891
George Burgess IVe1100f52016-02-02 22:46:49 +00001892MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00001893DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001894 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
1895 return Use->getDefiningAccess();
1896 return MA;
1897}
1898
1899MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
1900 MemoryAccess *StartingAccess, MemoryLocation &) {
1901 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
1902 return Use->getDefiningAccess();
1903 return StartingAccess;
1904}
George Burgess IV5f308972016-07-19 01:29:15 +00001905} // namespace llvm