blob: 241c9ddbbbaf1c9365c4543861907b5476710031 [file] [log] [blame]
George Burgess IVe1100f52016-02-02 22:46:49 +00001//===-- MemorySSA.cpp - Memory SSA Builder---------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------===//
9//
10// This file implements the MemorySSA class.
11//
12//===----------------------------------------------------------------===//
Daniel Berlin16ed57c2016-06-27 18:22:27 +000013#include "llvm/Transforms/Utils/MemorySSA.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000014#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/DenseSet.h"
16#include "llvm/ADT/DepthFirstIterator.h"
17#include "llvm/ADT/GraphTraits.h"
18#include "llvm/ADT/PostOrderIterator.h"
19#include "llvm/ADT/STLExtras.h"
George Burgess IV5f308972016-07-19 01:29:15 +000020#include "llvm/ADT/SmallBitVector.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000021#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/Analysis/AliasAnalysis.h"
25#include "llvm/Analysis/CFG.h"
26#include "llvm/Analysis/GlobalsModRef.h"
27#include "llvm/Analysis/IteratedDominanceFrontier.h"
28#include "llvm/Analysis/MemoryLocation.h"
29#include "llvm/Analysis/PHITransAddr.h"
30#include "llvm/IR/AssemblyAnnotationWriter.h"
31#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/Dominators.h"
33#include "llvm/IR/GlobalVariable.h"
34#include "llvm/IR/IRBuilder.h"
35#include "llvm/IR/IntrinsicInst.h"
36#include "llvm/IR/LLVMContext.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
39#include "llvm/IR/PatternMatch.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000040#include "llvm/Support/Debug.h"
41#include "llvm/Support/FormattedStream.h"
42#include "llvm/Transforms/Scalar.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000043#include <algorithm>
44
45#define DEBUG_TYPE "memoryssa"
46using namespace llvm;
47STATISTIC(NumClobberCacheLookups, "Number of Memory SSA version cache lookups");
48STATISTIC(NumClobberCacheHits, "Number of Memory SSA version cache hits");
49STATISTIC(NumClobberCacheInserts, "Number of MemorySSA version cache inserts");
Geoff Berryb96d3b22016-06-01 21:30:40 +000050
Geoff Berryefb0dd12016-06-14 21:19:40 +000051INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
Geoff Berryb96d3b22016-06-01 21:30:40 +000052 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000053INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
54INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Geoff Berryefb0dd12016-06-14 21:19:40 +000055INITIALIZE_PASS_END(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
56 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000057
Chad Rosier232e29e2016-07-06 21:20:47 +000058INITIALIZE_PASS_BEGIN(MemorySSAPrinterLegacyPass, "print-memoryssa",
59 "Memory SSA Printer", false, false)
60INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
61INITIALIZE_PASS_END(MemorySSAPrinterLegacyPass, "print-memoryssa",
62 "Memory SSA Printer", false, false)
63
Daniel Berlinc43aa5a2016-08-02 16:24:03 +000064static cl::opt<unsigned> MaxCheckLimit(
65 "memssa-check-limit", cl::Hidden, cl::init(100),
66 cl::desc("The maximum number of stores/phis MemorySSA"
67 "will consider trying to walk past (default = 100)"));
68
Chad Rosier232e29e2016-07-06 21:20:47 +000069static cl::opt<bool>
70 VerifyMemorySSA("verify-memoryssa", cl::init(false), cl::Hidden,
71 cl::desc("Verify MemorySSA in legacy printer pass."));
72
George Burgess IVe1100f52016-02-02 22:46:49 +000073namespace llvm {
George Burgess IVe1100f52016-02-02 22:46:49 +000074/// \brief An assembly annotator class to print Memory SSA information in
75/// comments.
76class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
77 friend class MemorySSA;
78 const MemorySSA *MSSA;
79
80public:
81 MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
82
83 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
84 formatted_raw_ostream &OS) {
85 if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
86 OS << "; " << *MA << "\n";
87 }
88
89 virtual void emitInstructionAnnot(const Instruction *I,
90 formatted_raw_ostream &OS) {
91 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
92 OS << "; " << *MA << "\n";
93 }
94};
George Burgess IV5f308972016-07-19 01:29:15 +000095}
George Burgess IVfd1f2f82016-06-24 21:02:12 +000096
George Burgess IV5f308972016-07-19 01:29:15 +000097namespace {
98struct UpwardsMemoryQuery {
99 // True if our original query started off as a call
100 bool IsCall;
101 // The pointer location we started the query with. This will be empty if
102 // IsCall is true.
103 MemoryLocation StartingLoc;
104 // This is the instruction we were querying about.
105 const Instruction *Inst;
106 // The MemoryAccess we actually got called with, used to test local domination
107 const MemoryAccess *OriginalAccess;
108
109 UpwardsMemoryQuery()
110 : IsCall(false), Inst(nullptr), OriginalAccess(nullptr) {}
111
112 UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
113 : IsCall(ImmutableCallSite(Inst)), Inst(Inst), OriginalAccess(Access) {
114 if (!IsCall)
115 StartingLoc = MemoryLocation::get(Inst);
116 }
117};
118
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000119static bool instructionClobbersQuery(MemoryDef *MD,
120 const MemoryLocation &UseLoc,
121 const Instruction *UseInst,
George Burgess IV5f308972016-07-19 01:29:15 +0000122 AliasAnalysis &AA) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000123 Instruction *DefInst = MD->getMemoryInst();
124 assert(DefInst && "Defining instruction not actually an instruction");
125 ImmutableCallSite UseCS(UseInst);
126 if (!UseCS)
127 return AA.getModRefInfo(DefInst, UseLoc) & MRI_Mod;
George Burgess IV5f308972016-07-19 01:29:15 +0000128
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000129 ModRefInfo I = AA.getModRefInfo(DefInst, UseCS);
George Burgess IV5f308972016-07-19 01:29:15 +0000130 return I != MRI_NoModRef;
131}
132
133/// Cache for our caching MemorySSA walker.
134class WalkerCache {
135 DenseMap<ConstMemoryAccessPair, MemoryAccess *> Accesses;
136 DenseMap<const MemoryAccess *, MemoryAccess *> Calls;
137
138public:
139 MemoryAccess *lookup(const MemoryAccess *MA, const MemoryLocation &Loc,
140 bool IsCall) const {
141 ++NumClobberCacheLookups;
142 MemoryAccess *R = IsCall ? Calls.lookup(MA) : Accesses.lookup({MA, Loc});
143 if (R)
144 ++NumClobberCacheHits;
145 return R;
146 }
147
148 bool insert(const MemoryAccess *MA, MemoryAccess *To,
149 const MemoryLocation &Loc, bool IsCall) {
150 // This is fine for Phis, since there are times where we can't optimize
151 // them. Making a def its own clobber is never correct, though.
152 assert((MA != To || isa<MemoryPhi>(MA)) &&
153 "Something can't clobber itself!");
154
155 ++NumClobberCacheInserts;
156 bool Inserted;
157 if (IsCall)
158 Inserted = Calls.insert({MA, To}).second;
159 else
160 Inserted = Accesses.insert({{MA, Loc}, To}).second;
161
162 return Inserted;
163 }
164
165 bool remove(const MemoryAccess *MA, const MemoryLocation &Loc, bool IsCall) {
166 return IsCall ? Calls.erase(MA) : Accesses.erase({MA, Loc});
167 }
168
169 void clear() {
170 Accesses.clear();
171 Calls.clear();
172 }
173
174 bool contains(const MemoryAccess *MA) const {
175 for (auto &P : Accesses)
176 if (P.first.first == MA || P.second == MA)
177 return true;
178 for (auto &P : Calls)
179 if (P.first == MA || P.second == MA)
180 return true;
181 return false;
182 }
183};
184
185/// Walks the defining uses of MemoryDefs. Stops after we hit something that has
186/// no defining use (e.g. a MemoryPhi or liveOnEntry). Note that, when comparing
187/// against a null def_chain_iterator, this will compare equal only after
188/// walking said Phi/liveOnEntry.
189struct def_chain_iterator
190 : public iterator_facade_base<def_chain_iterator, std::forward_iterator_tag,
191 MemoryAccess *> {
192 def_chain_iterator() : MA(nullptr) {}
193 def_chain_iterator(MemoryAccess *MA) : MA(MA) {}
194
195 MemoryAccess *operator*() const { return MA; }
196
197 def_chain_iterator &operator++() {
198 // N.B. liveOnEntry has a null defining access.
199 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
200 MA = MUD->getDefiningAccess();
201 else
202 MA = nullptr;
203 return *this;
204 }
205
206 bool operator==(const def_chain_iterator &O) const { return MA == O.MA; }
207
208private:
209 MemoryAccess *MA;
210};
211
212static iterator_range<def_chain_iterator>
213def_chain(MemoryAccess *MA, MemoryAccess *UpTo = nullptr) {
214#ifdef EXPENSIVE_CHECKS
215 assert((!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator()) &&
216 "UpTo isn't in the def chain!");
217#endif
218 return make_range(def_chain_iterator(MA), def_chain_iterator(UpTo));
219}
220
221/// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
222/// inbetween `Start` and `ClobberAt` can clobbers `Start`.
223///
224/// This is meant to be as simple and self-contained as possible. Because it
225/// uses no cache, etc., it can be relatively expensive.
226///
227/// \param Start The MemoryAccess that we want to walk from.
228/// \param ClobberAt A clobber for Start.
229/// \param StartLoc The MemoryLocation for Start.
230/// \param MSSA The MemorySSA isntance that Start and ClobberAt belong to.
231/// \param Query The UpwardsMemoryQuery we used for our search.
232/// \param AA The AliasAnalysis we used for our search.
233static void LLVM_ATTRIBUTE_UNUSED
234checkClobberSanity(MemoryAccess *Start, MemoryAccess *ClobberAt,
235 const MemoryLocation &StartLoc, const MemorySSA &MSSA,
236 const UpwardsMemoryQuery &Query, AliasAnalysis &AA) {
237 assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
238
239 if (MSSA.isLiveOnEntryDef(Start)) {
240 assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
241 "liveOnEntry must clobber itself");
242 return;
243 }
244
George Burgess IV5f308972016-07-19 01:29:15 +0000245 bool FoundClobber = false;
246 DenseSet<MemoryAccessPair> VisitedPhis;
247 SmallVector<MemoryAccessPair, 8> Worklist;
248 Worklist.emplace_back(Start, StartLoc);
249 // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
250 // is found, complain.
251 while (!Worklist.empty()) {
252 MemoryAccessPair MAP = Worklist.pop_back_val();
253 // All we care about is that nothing from Start to ClobberAt clobbers Start.
254 // We learn nothing from revisiting nodes.
255 if (!VisitedPhis.insert(MAP).second)
256 continue;
257
258 for (MemoryAccess *MA : def_chain(MAP.first)) {
259 if (MA == ClobberAt) {
260 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
261 // instructionClobbersQuery isn't essentially free, so don't use `|=`,
262 // since it won't let us short-circuit.
263 //
264 // Also, note that this can't be hoisted out of the `Worklist` loop,
265 // since MD may only act as a clobber for 1 of N MemoryLocations.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000266 FoundClobber =
267 FoundClobber || MSSA.isLiveOnEntryDef(MD) ||
268 instructionClobbersQuery(MD, MAP.second, Query.Inst, AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000269 }
270 break;
271 }
272
273 // We should never hit liveOnEntry, unless it's the clobber.
274 assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
275
276 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
277 (void)MD;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000278 assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA) &&
George Burgess IV5f308972016-07-19 01:29:15 +0000279 "Found clobber before reaching ClobberAt!");
280 continue;
281 }
282
283 assert(isa<MemoryPhi>(MA));
284 Worklist.append(upward_defs_begin({MA, MAP.second}), upward_defs_end());
285 }
286 }
287
288 // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
289 // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
290 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
291 "ClobberAt never acted as a clobber");
292}
293
294/// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
295/// in one class.
296class ClobberWalker {
297 /// Save a few bytes by using unsigned instead of size_t.
298 using ListIndex = unsigned;
299
300 /// Represents a span of contiguous MemoryDefs, potentially ending in a
301 /// MemoryPhi.
302 struct DefPath {
303 MemoryLocation Loc;
304 // Note that, because we always walk in reverse, Last will always dominate
305 // First. Also note that First and Last are inclusive.
306 MemoryAccess *First;
307 MemoryAccess *Last;
308 // N.B. Blocker is currently basically unused. The goal is to use it to make
309 // cache invalidation better, but we're not there yet.
310 MemoryAccess *Blocker;
311 Optional<ListIndex> Previous;
312
313 DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
314 Optional<ListIndex> Previous)
315 : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
316
317 DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
318 Optional<ListIndex> Previous)
319 : DefPath(Loc, Init, Init, Previous) {}
320 };
321
322 const MemorySSA &MSSA;
323 AliasAnalysis &AA;
324 DominatorTree &DT;
325 WalkerCache &WC;
326 UpwardsMemoryQuery *Query;
327 bool UseCache;
328
329 // Phi optimization bookkeeping
330 SmallVector<DefPath, 32> Paths;
331 DenseSet<ConstMemoryAccessPair> VisitedPhis;
332 DenseMap<const BasicBlock *, MemoryAccess *> WalkTargetCache;
333
334 void setUseCache(bool Use) { UseCache = Use; }
335 bool shouldIgnoreCache() const {
336 // UseCache will only be false when we're debugging, or when expensive
337 // checks are enabled. In either case, we don't care deeply about speed.
338 return LLVM_UNLIKELY(!UseCache);
339 }
340
341 void addCacheEntry(const MemoryAccess *What, MemoryAccess *To,
342 const MemoryLocation &Loc) const {
Daniel Berlin5c46b942016-07-19 22:49:43 +0000343// EXPENSIVE_CHECKS because most of these queries are redundant.
George Burgess IV5f308972016-07-19 01:29:15 +0000344#ifdef EXPENSIVE_CHECKS
345 assert(MSSA.dominates(To, What));
346#endif
347 if (shouldIgnoreCache())
348 return;
349 WC.insert(What, To, Loc, Query->IsCall);
350 }
351
352 MemoryAccess *lookupCache(const MemoryAccess *MA, const MemoryLocation &Loc) {
353 return shouldIgnoreCache() ? nullptr : WC.lookup(MA, Loc, Query->IsCall);
354 }
355
356 void cacheDefPath(const DefPath &DN, MemoryAccess *Target) const {
357 if (shouldIgnoreCache())
358 return;
359
360 for (MemoryAccess *MA : def_chain(DN.First, DN.Last))
361 addCacheEntry(MA, Target, DN.Loc);
362
363 // DefPaths only express the path we walked. So, DN.Last could either be a
364 // thing we want to cache, or not.
365 if (DN.Last != Target)
366 addCacheEntry(DN.Last, Target, DN.Loc);
367 }
368
369 /// Find the nearest def or phi that `From` can legally be optimized to.
370 ///
371 /// FIXME: Deduplicate this with MSSA::findDominatingDef. Ideally, MSSA should
372 /// keep track of this information for us, and allow us O(1) lookups of this
373 /// info.
374 MemoryAccess *getWalkTarget(const MemoryPhi *From) {
George Burgess IV5f308972016-07-19 01:29:15 +0000375 assert(From->getNumOperands() && "Phi with no operands?");
376
377 BasicBlock *BB = From->getBlock();
378 auto At = WalkTargetCache.find(BB);
379 if (At != WalkTargetCache.end())
380 return At->second;
381
382 SmallVector<const BasicBlock *, 8> ToCache;
383 ToCache.push_back(BB);
384
385 MemoryAccess *Result = MSSA.getLiveOnEntryDef();
386 DomTreeNode *Node = DT.getNode(BB);
387 while ((Node = Node->getIDom())) {
388 auto At = WalkTargetCache.find(BB);
389 if (At != WalkTargetCache.end()) {
390 Result = At->second;
391 break;
392 }
393
394 auto *Accesses = MSSA.getBlockAccesses(Node->getBlock());
395 if (Accesses) {
396 auto Iter = find_if(reverse(*Accesses), [](const MemoryAccess &MA) {
397 return !isa<MemoryUse>(MA);
398 });
399 if (Iter != Accesses->rend()) {
400 Result = const_cast<MemoryAccess *>(&*Iter);
401 break;
402 }
403 }
404
405 ToCache.push_back(Node->getBlock());
406 }
407
408 for (const BasicBlock *BB : ToCache)
409 WalkTargetCache.insert({BB, Result});
410 return Result;
411 }
412
413 /// Result of calling walkToPhiOrClobber.
414 struct UpwardsWalkResult {
415 /// The "Result" of the walk. Either a clobber, the last thing we walked, or
416 /// both.
417 MemoryAccess *Result;
418 bool IsKnownClobber;
419 bool FromCache;
420 };
421
422 /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
423 /// This will update Desc.Last as it walks. It will (optionally) also stop at
424 /// StopAt.
425 ///
426 /// This does not test for whether StopAt is a clobber
427 UpwardsWalkResult walkToPhiOrClobber(DefPath &Desc,
428 MemoryAccess *StopAt = nullptr) {
429 assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
430
431 for (MemoryAccess *Current : def_chain(Desc.Last)) {
432 Desc.Last = Current;
433 if (Current == StopAt)
434 return {Current, false, false};
435
436 if (auto *MD = dyn_cast<MemoryDef>(Current))
437 if (MSSA.isLiveOnEntryDef(MD) ||
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000438 instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA))
George Burgess IV5f308972016-07-19 01:29:15 +0000439 return {MD, true, false};
440
441 // Cache checks must be done last, because if Current is a clobber, the
442 // cache will contain the clobber for Current.
443 if (MemoryAccess *MA = lookupCache(Current, Desc.Loc))
444 return {MA, true, true};
445 }
446
447 assert(isa<MemoryPhi>(Desc.Last) &&
448 "Ended at a non-clobber that's not a phi?");
449 return {Desc.Last, false, false};
450 }
451
452 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
453 ListIndex PriorNode) {
454 auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),
455 upward_defs_end());
456 for (const MemoryAccessPair &P : UpwardDefs) {
457 PausedSearches.push_back(Paths.size());
458 Paths.emplace_back(P.second, P.first, PriorNode);
459 }
460 }
461
462 /// Represents a search that terminated after finding a clobber. This clobber
463 /// may or may not be present in the path of defs from LastNode..SearchStart,
464 /// since it may have been retrieved from cache.
465 struct TerminatedPath {
466 MemoryAccess *Clobber;
467 ListIndex LastNode;
468 };
469
470 /// Get an access that keeps us from optimizing to the given phi.
471 ///
472 /// PausedSearches is an array of indices into the Paths array. Its incoming
473 /// value is the indices of searches that stopped at the last phi optimization
474 /// target. It's left in an unspecified state.
475 ///
476 /// If this returns None, NewPaused is a vector of searches that terminated
477 /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
478 Optional<ListIndex>
479 getBlockingAccess(MemoryAccess *StopWhere,
480 SmallVectorImpl<ListIndex> &PausedSearches,
481 SmallVectorImpl<ListIndex> &NewPaused,
482 SmallVectorImpl<TerminatedPath> &Terminated) {
483 assert(!PausedSearches.empty() && "No searches to continue?");
484
485 // BFS vs DFS really doesn't make a difference here, so just do a DFS with
486 // PausedSearches as our stack.
487 while (!PausedSearches.empty()) {
488 ListIndex PathIndex = PausedSearches.pop_back_val();
489 DefPath &Node = Paths[PathIndex];
490
491 // If we've already visited this path with this MemoryLocation, we don't
492 // need to do so again.
493 //
494 // NOTE: That we just drop these paths on the ground makes caching
495 // behavior sporadic. e.g. given a diamond:
496 // A
497 // B C
498 // D
499 //
500 // ...If we walk D, B, A, C, we'll only cache the result of phi
501 // optimization for A, B, and D; C will be skipped because it dies here.
502 // This arguably isn't the worst thing ever, since:
503 // - We generally query things in a top-down order, so if we got below D
504 // without needing cache entries for {C, MemLoc}, then chances are
505 // that those cache entries would end up ultimately unused.
506 // - We still cache things for A, so C only needs to walk up a bit.
507 // If this behavior becomes problematic, we can fix without a ton of extra
508 // work.
509 if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
510 continue;
511
512 UpwardsWalkResult Res = walkToPhiOrClobber(Node, /*StopAt=*/StopWhere);
513 if (Res.IsKnownClobber) {
514 assert(Res.Result != StopWhere || Res.FromCache);
515 // If this wasn't a cache hit, we hit a clobber when walking. That's a
516 // failure.
517 if (!Res.FromCache || !MSSA.dominates(Res.Result, StopWhere))
518 return PathIndex;
519
520 // Otherwise, it's a valid thing to potentially optimize to.
521 Terminated.push_back({Res.Result, PathIndex});
522 continue;
523 }
524
525 if (Res.Result == StopWhere) {
526 // We've hit our target. Save this path off for if we want to continue
527 // walking.
528 NewPaused.push_back(PathIndex);
529 continue;
530 }
531
532 assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
533 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
534 }
535
536 return None;
537 }
538
539 template <typename T, typename Walker>
540 struct generic_def_path_iterator
541 : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
542 std::forward_iterator_tag, T *> {
543 generic_def_path_iterator() : W(nullptr), N(None) {}
544 generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
545
546 T &operator*() const { return curNode(); }
547
548 generic_def_path_iterator &operator++() {
549 N = curNode().Previous;
550 return *this;
551 }
552
553 bool operator==(const generic_def_path_iterator &O) const {
554 if (N.hasValue() != O.N.hasValue())
555 return false;
556 return !N.hasValue() || *N == *O.N;
557 }
558
559 private:
560 T &curNode() const { return W->Paths[*N]; }
561
562 Walker *W;
563 Optional<ListIndex> N;
564 };
565
566 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
567 using const_def_path_iterator =
568 generic_def_path_iterator<const DefPath, const ClobberWalker>;
569
570 iterator_range<def_path_iterator> def_path(ListIndex From) {
571 return make_range(def_path_iterator(this, From), def_path_iterator());
572 }
573
574 iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
575 return make_range(const_def_path_iterator(this, From),
576 const_def_path_iterator());
577 }
578
579 struct OptznResult {
580 /// The path that contains our result.
581 TerminatedPath PrimaryClobber;
582 /// The paths that we can legally cache back from, but that aren't
583 /// necessarily the result of the Phi optimization.
584 SmallVector<TerminatedPath, 4> OtherClobbers;
585 };
586
587 ListIndex defPathIndex(const DefPath &N) const {
588 // The assert looks nicer if we don't need to do &N
589 const DefPath *NP = &N;
590 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
591 "Out of bounds DefPath!");
592 return NP - &Paths.front();
593 }
594
595 /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
596 /// that act as legal clobbers. Note that this won't return *all* clobbers.
597 ///
598 /// Phi optimization algorithm tl;dr:
599 /// - Find the earliest def/phi, A, we can optimize to
600 /// - Find if all paths from the starting memory access ultimately reach A
601 /// - If not, optimization isn't possible.
602 /// - Otherwise, walk from A to another clobber or phi, A'.
603 /// - If A' is a def, we're done.
604 /// - If A' is a phi, try to optimize it.
605 ///
606 /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
607 /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
608 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
609 const MemoryLocation &Loc) {
610 assert(Paths.empty() && VisitedPhis.empty() &&
611 "Reset the optimization state.");
612
613 Paths.emplace_back(Loc, Start, Phi, None);
614 // Stores how many "valid" optimization nodes we had prior to calling
615 // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
616 auto PriorPathsSize = Paths.size();
617
618 SmallVector<ListIndex, 16> PausedSearches;
619 SmallVector<ListIndex, 8> NewPaused;
620 SmallVector<TerminatedPath, 4> TerminatedPaths;
621
622 addSearches(Phi, PausedSearches, 0);
623
624 // Moves the TerminatedPath with the "most dominated" Clobber to the end of
625 // Paths.
626 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
627 assert(!Paths.empty() && "Need a path to move");
George Burgess IV5f308972016-07-19 01:29:15 +0000628 auto Dom = Paths.begin();
629 for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
630 if (!MSSA.dominates(I->Clobber, Dom->Clobber))
631 Dom = I;
632 auto Last = Paths.end() - 1;
633 if (Last != Dom)
634 std::iter_swap(Last, Dom);
635 };
636
637 MemoryPhi *Current = Phi;
638 while (1) {
639 assert(!MSSA.isLiveOnEntryDef(Current) &&
640 "liveOnEntry wasn't treated as a clobber?");
641
642 MemoryAccess *Target = getWalkTarget(Current);
643 // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
644 // optimization for the prior phi.
645 assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
646 return MSSA.dominates(P.Clobber, Target);
647 }));
648
649 // FIXME: This is broken, because the Blocker may be reported to be
650 // liveOnEntry, and we'll happily wait for that to disappear (read: never)
651 // For the moment, this is fine, since we do basically nothing with
652 // blocker info.
653 if (Optional<ListIndex> Blocker = getBlockingAccess(
654 Target, PausedSearches, NewPaused, TerminatedPaths)) {
655 MemoryAccess *BlockingAccess = Paths[*Blocker].Last;
656 // Cache our work on the blocking node, since we know that's correct.
657 cacheDefPath(Paths[*Blocker], BlockingAccess);
658
659 // Find the node we started at. We can't search based on N->Last, since
660 // we may have gone around a loop with a different MemoryLocation.
661 auto Iter = find_if(def_path(*Blocker), [&](const DefPath &N) {
662 return defPathIndex(N) < PriorPathsSize;
663 });
664 assert(Iter != def_path_iterator());
665
666 DefPath &CurNode = *Iter;
667 assert(CurNode.Last == Current);
668 CurNode.Blocker = BlockingAccess;
669
670 // Two things:
671 // A. We can't reliably cache all of NewPaused back. Consider a case
672 // where we have two paths in NewPaused; one of which can't optimize
673 // above this phi, whereas the other can. If we cache the second path
674 // back, we'll end up with suboptimal cache entries. We can handle
675 // cases like this a bit better when we either try to find all
676 // clobbers that block phi optimization, or when our cache starts
677 // supporting unfinished searches.
678 // B. We can't reliably cache TerminatedPaths back here without doing
679 // extra checks; consider a case like:
680 // T
681 // / \
682 // D C
683 // \ /
684 // S
685 // Where T is our target, C is a node with a clobber on it, D is a
686 // diamond (with a clobber *only* on the left or right node, N), and
687 // S is our start. Say we walk to D, through the node opposite N
688 // (read: ignoring the clobber), and see a cache entry in the top
689 // node of D. That cache entry gets put into TerminatedPaths. We then
690 // walk up to C (N is later in our worklist), find the clobber, and
691 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
692 // the bottom part of D to the cached clobber, ignoring the clobber
693 // in N. Again, this problem goes away if we start tracking all
694 // blockers for a given phi optimization.
695 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
696 return {Result, {}};
697 }
698
699 // If there's nothing left to search, then all paths led to valid clobbers
700 // that we got from our cache; pick the nearest to the start, and allow
701 // the rest to be cached back.
702 if (NewPaused.empty()) {
703 MoveDominatedPathToEnd(TerminatedPaths);
704 TerminatedPath Result = TerminatedPaths.pop_back_val();
705 return {Result, std::move(TerminatedPaths)};
706 }
707
708 MemoryAccess *DefChainEnd = nullptr;
709 SmallVector<TerminatedPath, 4> Clobbers;
710 for (ListIndex Paused : NewPaused) {
711 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
712 if (WR.IsKnownClobber)
713 Clobbers.push_back({WR.Result, Paused});
714 else
715 // Micro-opt: If we hit the end of the chain, save it.
716 DefChainEnd = WR.Result;
717 }
718
719 if (!TerminatedPaths.empty()) {
720 // If we couldn't find the dominating phi/liveOnEntry in the above loop,
721 // do it now.
722 if (!DefChainEnd)
723 for (MemoryAccess *MA : def_chain(Target))
724 DefChainEnd = MA;
725
726 // If any of the terminated paths don't dominate the phi we'll try to
727 // optimize, we need to figure out what they are and quit.
728 const BasicBlock *ChainBB = DefChainEnd->getBlock();
729 for (const TerminatedPath &TP : TerminatedPaths) {
730 // Because we know that DefChainEnd is as "high" as we can go, we
731 // don't need local dominance checks; BB dominance is sufficient.
732 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
733 Clobbers.push_back(TP);
734 }
735 }
736
737 // If we have clobbers in the def chain, find the one closest to Current
738 // and quit.
739 if (!Clobbers.empty()) {
740 MoveDominatedPathToEnd(Clobbers);
741 TerminatedPath Result = Clobbers.pop_back_val();
742 return {Result, std::move(Clobbers)};
743 }
744
745 assert(all_of(NewPaused,
746 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
747
748 // Because liveOnEntry is a clobber, this must be a phi.
749 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
750
751 PriorPathsSize = Paths.size();
752 PausedSearches.clear();
753 for (ListIndex I : NewPaused)
754 addSearches(DefChainPhi, PausedSearches, I);
755 NewPaused.clear();
756
757 Current = DefChainPhi;
758 }
759 }
760
761 /// Caches everything in an OptznResult.
762 void cacheOptResult(const OptznResult &R) {
763 if (R.OtherClobbers.empty()) {
764 // If we're not going to be caching OtherClobbers, don't bother with
765 // marking visited/etc.
766 for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode))
767 cacheDefPath(N, R.PrimaryClobber.Clobber);
768 return;
769 }
770
771 // PrimaryClobber is our answer. If we can cache anything back, we need to
772 // stop caching when we visit PrimaryClobber.
773 SmallBitVector Visited(Paths.size());
774 for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode)) {
775 Visited[defPathIndex(N)] = true;
776 cacheDefPath(N, R.PrimaryClobber.Clobber);
777 }
778
779 for (const TerminatedPath &P : R.OtherClobbers) {
780 for (const DefPath &N : const_def_path(P.LastNode)) {
781 ListIndex NIndex = defPathIndex(N);
782 if (Visited[NIndex])
783 break;
784 Visited[NIndex] = true;
785 cacheDefPath(N, P.Clobber);
786 }
787 }
788 }
789
790 void verifyOptResult(const OptznResult &R) const {
791 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
792 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
793 }));
794 }
795
796 void resetPhiOptznState() {
797 Paths.clear();
798 VisitedPhis.clear();
799 }
800
801public:
802 ClobberWalker(const MemorySSA &MSSA, AliasAnalysis &AA, DominatorTree &DT,
803 WalkerCache &WC)
804 : MSSA(MSSA), AA(AA), DT(DT), WC(WC), UseCache(true) {}
805
806 void reset() { WalkTargetCache.clear(); }
807
808 /// Finds the nearest clobber for the given query, optimizing phis if
809 /// possible.
810 MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q,
811 bool UseWalkerCache = true) {
812 setUseCache(UseWalkerCache);
813 Query = &Q;
814
815 MemoryAccess *Current = Start;
816 // This walker pretends uses don't exist. If we're handed one, silently grab
817 // its def. (This has the nice side-effect of ensuring we never cache uses)
818 if (auto *MU = dyn_cast<MemoryUse>(Start))
819 Current = MU->getDefiningAccess();
820
821 DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
822 // Fast path for the overly-common case (no crazy phi optimization
823 // necessary)
824 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000825 MemoryAccess *Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000826 if (WalkResult.IsKnownClobber) {
827 cacheDefPath(FirstDesc, WalkResult.Result);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000828 Result = WalkResult.Result;
829 } else {
830 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
831 Current, Q.StartingLoc);
832 verifyOptResult(OptRes);
833 cacheOptResult(OptRes);
834 resetPhiOptznState();
835 Result = OptRes.PrimaryClobber.Clobber;
George Burgess IV5f308972016-07-19 01:29:15 +0000836 }
837
George Burgess IV5f308972016-07-19 01:29:15 +0000838#ifdef EXPENSIVE_CHECKS
George Burgess IV93ea19b2016-07-24 07:03:49 +0000839 checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000840#endif
George Burgess IV93ea19b2016-07-24 07:03:49 +0000841 return Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000842 }
843};
844
845struct RenamePassData {
846 DomTreeNode *DTN;
847 DomTreeNode::const_iterator ChildIt;
848 MemoryAccess *IncomingVal;
849
850 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
851 MemoryAccess *M)
852 : DTN(D), ChildIt(It), IncomingVal(M) {}
853 void swap(RenamePassData &RHS) {
854 std::swap(DTN, RHS.DTN);
855 std::swap(ChildIt, RHS.ChildIt);
856 std::swap(IncomingVal, RHS.IncomingVal);
857 }
858};
859} // anonymous namespace
860
861namespace llvm {
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000862/// \brief A MemorySSAWalker that does AA walks and caching of lookups to
863/// disambiguate accesses.
864///
865/// FIXME: The current implementation of this can take quadratic space in rare
866/// cases. This can be fixed, but it is something to note until it is fixed.
867///
868/// In order to trigger this behavior, you need to store to N distinct locations
869/// (that AA can prove don't alias), perform M stores to other memory
870/// locations that AA can prove don't alias any of the initial N locations, and
871/// then load from all of the N locations. In this case, we insert M cache
872/// entries for each of the N loads.
873///
874/// For example:
875/// define i32 @foo() {
876/// %a = alloca i32, align 4
877/// %b = alloca i32, align 4
878/// store i32 0, i32* %a, align 4
879/// store i32 0, i32* %b, align 4
880///
881/// ; Insert M stores to other memory that doesn't alias %a or %b here
882///
883/// %c = load i32, i32* %a, align 4 ; Caches M entries in
884/// ; CachedUpwardsClobberingAccess for the
885/// ; MemoryLocation %a
886/// %d = load i32, i32* %b, align 4 ; Caches M entries in
887/// ; CachedUpwardsClobberingAccess for the
888/// ; MemoryLocation %b
889///
890/// ; For completeness' sake, loading %a or %b again would not cache *another*
891/// ; M entries.
892/// %r = add i32 %c, %d
893/// ret i32 %r
894/// }
895class MemorySSA::CachingWalker final : public MemorySSAWalker {
George Burgess IV5f308972016-07-19 01:29:15 +0000896 WalkerCache Cache;
897 ClobberWalker Walker;
898 bool AutoResetWalker;
899
900 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, UpwardsMemoryQuery &);
901 void verifyRemoved(MemoryAccess *);
902
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000903public:
904 CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *);
905 ~CachingWalker() override;
906
George Burgess IV400ae402016-07-20 19:51:34 +0000907 using MemorySSAWalker::getClobberingMemoryAccess;
908 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override;
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000909 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
910 MemoryLocation &) override;
911 void invalidateInfo(MemoryAccess *) override;
912
George Burgess IV5f308972016-07-19 01:29:15 +0000913 /// Whether we call resetClobberWalker() after each time we *actually* walk to
914 /// answer a clobber query.
915 void setAutoResetWalker(bool AutoReset) { AutoResetWalker = AutoReset; }
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000916
George Burgess IV5f308972016-07-19 01:29:15 +0000917 /// Drop the walker's persistent data structures. At the moment, this means
918 /// "drop the walker's cache of BasicBlocks ->
919 /// earliest-MemoryAccess-we-can-optimize-to". This is necessary if we're
920 /// going to have DT updates, if we remove MemoryAccesses, etc.
921 void resetClobberWalker() { Walker.reset(); }
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000922};
George Burgess IVe1100f52016-02-02 22:46:49 +0000923
George Burgess IVe1100f52016-02-02 22:46:49 +0000924/// \brief Rename a single basic block into MemorySSA form.
925/// Uses the standard SSA renaming algorithm.
926/// \returns The new incoming value.
927MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB,
928 MemoryAccess *IncomingVal) {
929 auto It = PerBlockAccesses.find(BB);
930 // Skip most processing if the list is empty.
931 if (It != PerBlockAccesses.end()) {
Daniel Berlinada263d2016-06-20 20:21:33 +0000932 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000933 for (MemoryAccess &L : *Accesses) {
934 switch (L.getValueID()) {
935 case Value::MemoryUseVal:
936 cast<MemoryUse>(&L)->setDefiningAccess(IncomingVal);
937 break;
938 case Value::MemoryDefVal:
939 // We can't legally optimize defs, because we only allow single
940 // memory phis/uses on operations, and if we optimize these, we can
941 // end up with multiple reaching defs. Uses do not have this
942 // problem, since they do not produce a value
943 cast<MemoryDef>(&L)->setDefiningAccess(IncomingVal);
944 IncomingVal = &L;
945 break;
946 case Value::MemoryPhiVal:
947 IncomingVal = &L;
948 break;
949 }
950 }
951 }
952
953 // Pass through values to our successors
954 for (const BasicBlock *S : successors(BB)) {
955 auto It = PerBlockAccesses.find(S);
956 // Rename the phi nodes in our successor block
957 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
958 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +0000959 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000960 auto *Phi = cast<MemoryPhi>(&Accesses->front());
George Burgess IVe1100f52016-02-02 22:46:49 +0000961 Phi->addIncoming(IncomingVal, BB);
962 }
963
964 return IncomingVal;
965}
966
967/// \brief This is the standard SSA renaming algorithm.
968///
969/// We walk the dominator tree in preorder, renaming accesses, and then filling
970/// in phi nodes in our successors.
971void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
972 SmallPtrSet<BasicBlock *, 16> &Visited) {
973 SmallVector<RenamePassData, 32> WorkStack;
974 IncomingVal = renameBlock(Root->getBlock(), IncomingVal);
975 WorkStack.push_back({Root, Root->begin(), IncomingVal});
976 Visited.insert(Root->getBlock());
977
978 while (!WorkStack.empty()) {
979 DomTreeNode *Node = WorkStack.back().DTN;
980 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
981 IncomingVal = WorkStack.back().IncomingVal;
982
983 if (ChildIt == Node->end()) {
984 WorkStack.pop_back();
985 } else {
986 DomTreeNode *Child = *ChildIt;
987 ++WorkStack.back().ChildIt;
988 BasicBlock *BB = Child->getBlock();
989 Visited.insert(BB);
990 IncomingVal = renameBlock(BB, IncomingVal);
991 WorkStack.push_back({Child, Child->begin(), IncomingVal});
992 }
993 }
994}
995
996/// \brief Compute dominator levels, used by the phi insertion algorithm above.
997void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) {
998 for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode());
999 DFI != DFE; ++DFI)
1000 DomLevels[*DFI] = DFI.getPathLength() - 1;
1001}
1002
George Burgess IVa362b092016-07-06 00:28:43 +00001003/// \brief This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +00001004/// unreachable blocks, and marking all other unreachable MemoryAccess's as
1005/// being uses of the live on entry definition.
1006void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
1007 assert(!DT->isReachableFromEntry(BB) &&
1008 "Reachable block found while handling unreachable blocks");
1009
Daniel Berlinfc7e6512016-07-06 05:32:05 +00001010 // Make sure phi nodes in our reachable successors end up with a
1011 // LiveOnEntryDef for our incoming edge, even though our block is forward
1012 // unreachable. We could just disconnect these blocks from the CFG fully,
1013 // but we do not right now.
1014 for (const BasicBlock *S : successors(BB)) {
1015 if (!DT->isReachableFromEntry(S))
1016 continue;
1017 auto It = PerBlockAccesses.find(S);
1018 // Rename the phi nodes in our successor block
1019 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1020 continue;
1021 AccessList *Accesses = It->second.get();
1022 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1023 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1024 }
1025
George Burgess IVe1100f52016-02-02 22:46:49 +00001026 auto It = PerBlockAccesses.find(BB);
1027 if (It == PerBlockAccesses.end())
1028 return;
1029
1030 auto &Accesses = It->second;
1031 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1032 auto Next = std::next(AI);
1033 // If we have a phi, just remove it. We are going to replace all
1034 // users with live on entry.
1035 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1036 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1037 else
1038 Accesses->erase(AI);
1039 AI = Next;
1040 }
1041}
1042
Geoff Berryb96d3b22016-06-01 21:30:40 +00001043MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
1044 : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
1045 NextID(0) {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001046 buildMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001047}
1048
1049MemorySSA::MemorySSA(MemorySSA &&MSSA)
1050 : AA(MSSA.AA), DT(MSSA.DT), F(MSSA.F),
1051 ValueToMemoryAccess(std::move(MSSA.ValueToMemoryAccess)),
1052 PerBlockAccesses(std::move(MSSA.PerBlockAccesses)),
1053 LiveOnEntryDef(std::move(MSSA.LiveOnEntryDef)),
1054 Walker(std::move(MSSA.Walker)), NextID(MSSA.NextID) {
1055 // Update the Walker MSSA pointer so it doesn't point to the moved-from MSSA
1056 // object any more.
1057 Walker->MSSA = this;
1058}
George Burgess IVe1100f52016-02-02 22:46:49 +00001059
1060MemorySSA::~MemorySSA() {
1061 // Drop all our references
1062 for (const auto &Pair : PerBlockAccesses)
1063 for (MemoryAccess &MA : *Pair.second)
1064 MA.dropAllReferences();
1065}
1066
Daniel Berlin14300262016-06-21 18:39:20 +00001067MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001068 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1069
1070 if (Res.second)
Daniel Berlinada263d2016-06-20 20:21:33 +00001071 Res.first->second = make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001072 return Res.first->second.get();
1073}
1074
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001075/// Our current alias analysis API differentiates heavily between calls and
1076/// non-calls, and functions called on one usually assert on the other.
1077/// This class encapsulates the distinction to simplify other code that wants
1078/// "Memory affecting instructions and related data" to use as a key.
1079/// For example, this class is used as a densemap key in the use optimizer.
1080class MemoryLocOrCall {
1081public:
1082 MemoryLocOrCall() : IsCall(false) {}
1083 MemoryLocOrCall(MemoryUseOrDef *MUD)
1084 : MemoryLocOrCall(MUD->getMemoryInst()) {}
1085
1086 MemoryLocOrCall(Instruction *Inst) {
1087 if (ImmutableCallSite(Inst)) {
1088 IsCall = true;
1089 CS = ImmutableCallSite(Inst);
1090 } else {
1091 IsCall = false;
1092 // There is no such thing as a memorylocation for a fence inst, and it is
1093 // unique in that regard.
1094 if (!isa<FenceInst>(Inst))
1095 Loc = MemoryLocation::get(Inst);
1096 }
1097 }
1098
1099 explicit MemoryLocOrCall(MemoryLocation Loc) : IsCall(false), Loc(Loc) {}
1100
1101 bool IsCall;
1102 ImmutableCallSite getCS() const {
1103 assert(IsCall);
1104 return CS;
1105 }
1106 MemoryLocation getLoc() const {
1107 assert(!IsCall);
1108 return Loc;
1109 }
1110 bool operator==(const MemoryLocOrCall &Other) const {
1111 if (IsCall != Other.IsCall)
1112 return false;
1113
1114 if (IsCall)
1115 return CS.getCalledValue() == Other.CS.getCalledValue();
1116 else
1117 return Loc == Other.Loc;
1118 }
1119
1120private:
1121 union {
1122 ImmutableCallSite CS;
1123 MemoryLocation Loc;
1124 };
1125};
1126
1127template <> struct DenseMapInfo<MemoryLocOrCall> {
1128 static inline MemoryLocOrCall getEmptyKey() {
1129 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getEmptyKey());
1130 }
1131 static inline MemoryLocOrCall getTombstoneKey() {
1132 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getTombstoneKey());
1133 }
1134 static unsigned getHashValue(const MemoryLocOrCall &MLOC) {
1135 if (MLOC.IsCall)
1136 return hash_combine(MLOC.IsCall,
1137 DenseMapInfo<const Value *>::getHashValue(
1138 MLOC.getCS().getCalledValue()));
1139 else
1140 return hash_combine(
1141 MLOC.IsCall,
1142 DenseMapInfo<MemoryLocation>::getHashValue(MLOC.getLoc()));
1143 }
1144 static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS) {
1145 return LHS == RHS;
1146 }
1147};
1148
1149/// This class is a batch walker of all MemoryUse's in the program, and points
1150/// their defining access at the thing that actually clobbers them. Because it
1151/// is a batch walker that touches everything, it does not operate like the
1152/// other walkers. This walker is basically performing a top-down SSA renaming
1153/// pass, where the version stack is used as the cache. This enables it to be
1154/// significantly more time and memory efficient than using the regular walker,
1155/// which is walking bottom-up.
1156class MemorySSA::OptimizeUses {
1157public:
1158 OptimizeUses(MemorySSA *MSSA, MemorySSAWalker *Walker, AliasAnalysis *AA,
1159 DominatorTree *DT)
1160 : MSSA(MSSA), Walker(Walker), AA(AA), DT(DT) {
1161 Walker = MSSA->getWalker();
1162 }
1163
1164 void optimizeUses();
1165
1166private:
1167 /// This represents where a given memorylocation is in the stack.
1168 struct MemlocStackInfo {
1169 // This essentially is keeping track of versions of the stack. Whenever
1170 // the stack changes due to pushes or pops, these versions increase.
1171 unsigned long StackEpoch;
1172 unsigned long PopEpoch;
1173 // This is the lower bound of places on the stack to check. It is equal to
1174 // the place the last stack walk ended.
1175 // Note: Correctness depends on this being initialized to 0, which densemap
1176 // does
1177 unsigned long LowerBound;
1178 // This is where the last walk for this memory location ended.
1179 unsigned long LastKill;
1180 bool LastKillValid;
1181 };
1182 void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1183 SmallVectorImpl<MemoryAccess *> &,
1184 DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
1185 MemorySSA *MSSA;
1186 MemorySSAWalker *Walker;
1187 AliasAnalysis *AA;
1188 DominatorTree *DT;
1189};
1190
1191static bool instructionClobbersQuery(MemoryDef *MD,
1192 const MemoryLocOrCall &UseMLOC,
1193 AliasAnalysis &AA) {
1194 Instruction *DefInst = MD->getMemoryInst();
1195 assert(DefInst && "Defining instruction not actually an instruction");
1196 if (!UseMLOC.IsCall)
1197 return AA.getModRefInfo(DefInst, UseMLOC.getLoc()) & MRI_Mod;
1198
1199 ModRefInfo I = AA.getModRefInfo(DefInst, UseMLOC.getCS());
1200 return I != MRI_NoModRef;
1201}
1202
1203/// Optimize the uses in a given block This is basically the SSA renaming
1204/// algorithm, with one caveat: We are able to use a single stack for all
1205/// MemoryUses. This is because the set of *possible* reaching MemoryDefs is
1206/// the same for every MemoryUse. The *actual* clobbering MemoryDef is just
1207/// going to be some position in that stack of possible ones.
1208///
1209/// We track the stack positions that each MemoryLocation needs
1210/// to check, and last ended at. This is because we only want to check the
1211/// things that changed since last time. The same MemoryLocation should
1212/// get clobbered by the same store (getModRefInfo does not use invariantness or
1213/// things like this, and if they start, we can modify MemoryLocOrCall to
1214/// include relevant data)
1215void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1216 const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1217 SmallVectorImpl<MemoryAccess *> &VersionStack,
1218 DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
1219
1220 /// If no accesses, nothing to do.
1221 MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
1222 if (Accesses == nullptr)
1223 return;
1224
1225 // Pop everything that doesn't dominate the current block off the stack,
1226 // increment the PopEpoch to account for this.
1227 while (!VersionStack.empty()) {
1228 BasicBlock *BackBlock = VersionStack.back()->getBlock();
1229 if (DT->dominates(BackBlock, BB))
1230 break;
1231 while (VersionStack.back()->getBlock() == BackBlock)
1232 VersionStack.pop_back();
1233 ++PopEpoch;
1234 }
1235
1236 for (MemoryAccess &MA : *Accesses) {
1237 auto *MU = dyn_cast<MemoryUse>(&MA);
1238 if (!MU) {
1239 VersionStack.push_back(&MA);
1240 ++StackEpoch;
1241 continue;
1242 }
1243
1244 MemoryLocOrCall UseMLOC(MU);
1245 auto &LocInfo = LocStackInfo[UseMLOC];
1246 // If the pop epoch changed, if means we've removed stuff from top of
1247 // stack due to changing blocks. We may have to reset the lower bound or
1248 // last kill info.
1249 if (LocInfo.PopEpoch != PopEpoch) {
1250 LocInfo.PopEpoch = PopEpoch;
1251 LocInfo.StackEpoch = StackEpoch;
1252 // If the lower bound was in the info we popped, we have to reset it.
1253 if (LocInfo.LowerBound >= VersionStack.size()) {
1254 // Reset the lower bound of things to check.
1255 // TODO: Some day we should be able to reset to last kill, rather than
1256 // 0.
1257
1258 LocInfo.LowerBound = 0;
1259 LocInfo.LastKillValid = false;
1260 }
1261 } else if (LocInfo.StackEpoch != StackEpoch) {
1262 // If all that has changed is the StackEpoch, we only have to check the
1263 // new things on the stack, because we've checked everything before. In
1264 // this case, the lower bound of things to check remains the same.
1265 LocInfo.PopEpoch = PopEpoch;
1266 LocInfo.StackEpoch = StackEpoch;
1267 }
1268 if (!LocInfo.LastKillValid) {
1269 LocInfo.LastKill = VersionStack.size() - 1;
1270 LocInfo.LastKillValid = true;
1271 }
1272
1273 // At this point, we should have corrected last kill and LowerBound to be
1274 // in bounds.
1275 assert(LocInfo.LowerBound < VersionStack.size() &&
1276 "Lower bound out of range");
1277 assert(LocInfo.LastKill < VersionStack.size() &&
1278 "Last kill info out of range");
1279 // In any case, the new upper bound is the top of the stack.
1280 unsigned long UpperBound = VersionStack.size() - 1;
1281
1282 if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
1283 DEBUG(dbgs() << "We are being asked to check up to "
1284 << UpperBound - LocInfo.LowerBound
1285 << " loads and stores, so we didn't.\n");
1286 // Because we did not walk, LastKill is no longer valid, as this may
1287 // have been a kill.
1288 LocInfo.LastKillValid = false;
1289 continue;
1290 }
1291 bool FoundClobberResult = false;
1292 while (UpperBound > LocInfo.LowerBound) {
1293 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1294 // For phis, use the walker, see where we ended up, go there
1295 Instruction *UseInst = MU->getMemoryInst();
1296 MemoryAccess *Result = Walker->getClobberingMemoryAccess(UseInst);
1297 // We are guaranteed to find it or something is wrong
1298 while (VersionStack[UpperBound] != Result) {
1299 assert(UpperBound != 0);
1300 --UpperBound;
1301 }
1302 FoundClobberResult = true;
1303 break;
1304 }
1305
1306 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
1307
1308 if (instructionClobbersQuery(MD, UseMLOC, *AA)) {
1309 FoundClobberResult = true;
1310 break;
1311 }
1312 --UpperBound;
1313 }
1314 // At the end of this loop, UpperBound is either a clobber, or lower bound
1315 // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1316 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
1317 MU->setDefiningAccess(VersionStack[UpperBound]);
1318 // We were last killed now by where we got to
1319 LocInfo.LastKill = UpperBound;
1320 } else {
1321 // Otherwise, we checked all the new ones, and now we know we can get to
1322 // LastKill.
1323 MU->setDefiningAccess(VersionStack[LocInfo.LastKill]);
1324 }
1325 LocInfo.LowerBound = VersionStack.size() - 1;
1326 }
1327}
1328
1329/// Optimize uses to point to their actual clobbering definitions.
1330void MemorySSA::OptimizeUses::optimizeUses() {
1331
1332 // We perform a non-recursive top-down dominator tree walk
1333 struct StackInfo {
1334 const DomTreeNode *Node;
1335 DomTreeNode::const_iterator Iter;
1336 };
1337
1338 SmallVector<MemoryAccess *, 16> VersionStack;
1339 SmallVector<StackInfo, 16> DomTreeWorklist;
1340 DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
1341 DomTreeWorklist.push_back({DT->getRootNode(), DT->getRootNode()->begin()});
1342 // Bottom of the version stack is always live on entry.
1343 VersionStack.push_back(MSSA->getLiveOnEntryDef());
1344
1345 unsigned long StackEpoch = 1;
1346 unsigned long PopEpoch = 1;
1347 while (!DomTreeWorklist.empty()) {
1348 const auto *DomNode = DomTreeWorklist.back().Node;
1349 const auto DomIter = DomTreeWorklist.back().Iter;
1350 BasicBlock *BB = DomNode->getBlock();
1351 optimizeUsesInBlock(BB, StackEpoch, PopEpoch, VersionStack, LocStackInfo);
1352 if (DomIter == DomNode->end()) {
1353 // Hit the end, pop the worklist
1354 DomTreeWorklist.pop_back();
1355 continue;
1356 }
1357 // Move the iterator to the next child for the next time we get to process
1358 // children
1359 ++DomTreeWorklist.back().Iter;
1360
1361 // Now visit the next child
1362 DomTreeWorklist.push_back({*DomIter, (*DomIter)->begin()});
1363 }
1364}
1365
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001366void MemorySSA::buildMemorySSA() {
George Burgess IVe1100f52016-02-02 22:46:49 +00001367 // We create an access to represent "live on entry", for things like
1368 // arguments or users of globals, where the memory they use is defined before
1369 // the beginning of the function. We do not actually insert it into the IR.
1370 // We do not define a live on exit for the immediate uses, and thus our
1371 // semantics do *not* imply that something with no immediate uses can simply
1372 // be removed.
1373 BasicBlock &StartingPoint = F.getEntryBlock();
1374 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
1375 &StartingPoint, NextID++);
1376
1377 // We maintain lists of memory accesses per-block, trading memory for time. We
1378 // could just look up the memory access for every possible instruction in the
1379 // stream.
1380 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001381 SmallPtrSet<BasicBlock *, 32> DefUseBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001382 // Go through each block, figure out where defs occur, and chain together all
1383 // the accesses.
1384 for (BasicBlock &B : F) {
Daniel Berlin7898ca62016-02-07 01:52:15 +00001385 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001386 AccessList *Accesses = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001387 for (Instruction &I : B) {
Peter Collingbourneffecb142016-05-26 01:19:17 +00001388 MemoryUseOrDef *MUD = createNewAccess(&I);
George Burgess IVb42b7622016-03-11 19:34:03 +00001389 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001390 continue;
George Burgess IV3887a412016-03-21 21:25:39 +00001391 InsertIntoDef |= isa<MemoryDef>(MUD);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001392
George Burgess IVe1100f52016-02-02 22:46:49 +00001393 if (!Accesses)
1394 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001395 Accesses->push_back(MUD);
George Burgess IVe1100f52016-02-02 22:46:49 +00001396 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001397 if (InsertIntoDef)
1398 DefiningBlocks.insert(&B);
George Burgess IV3887a412016-03-21 21:25:39 +00001399 if (Accesses)
Daniel Berlin1b51a292016-02-07 01:52:19 +00001400 DefUseBlocks.insert(&B);
1401 }
1402
1403 // Compute live-in.
1404 // Live in is normally defined as "all the blocks on the path from each def to
1405 // each of it's uses".
1406 // MemoryDef's are implicit uses of previous state, so they are also uses.
1407 // This means we don't really have def-only instructions. The only
1408 // MemoryDef's that are not really uses are those that are of the LiveOnEntry
1409 // variable (because LiveOnEntry can reach anywhere, and every def is a
1410 // must-kill of LiveOnEntry).
1411 // In theory, you could precisely compute live-in by using alias-analysis to
1412 // disambiguate defs and uses to see which really pair up with which.
1413 // In practice, this would be really expensive and difficult. So we simply
1414 // assume all defs are also uses that need to be kept live.
1415 // Because of this, the end result of this live-in computation will be "the
1416 // entire set of basic blocks that reach any use".
1417
1418 SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
1419 SmallVector<BasicBlock *, 64> LiveInBlockWorklist(DefUseBlocks.begin(),
1420 DefUseBlocks.end());
1421 // Now that we have a set of blocks where a value is live-in, recursively add
1422 // predecessors until we find the full region the value is live.
1423 while (!LiveInBlockWorklist.empty()) {
1424 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
1425
1426 // The block really is live in here, insert it into the set. If already in
1427 // the set, then it has already been processed.
1428 if (!LiveInBlocks.insert(BB).second)
1429 continue;
1430
1431 // Since the value is live into BB, it is either defined in a predecessor or
1432 // live into it to.
1433 LiveInBlockWorklist.append(pred_begin(BB), pred_end(BB));
George Burgess IVe1100f52016-02-02 22:46:49 +00001434 }
1435
1436 // Determine where our MemoryPhi's should go
Daniel Berlin77fa84e2016-04-19 06:13:28 +00001437 ForwardIDFCalculator IDFs(*DT);
George Burgess IVe1100f52016-02-02 22:46:49 +00001438 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001439 IDFs.setLiveInBlocks(LiveInBlocks);
George Burgess IVe1100f52016-02-02 22:46:49 +00001440 SmallVector<BasicBlock *, 32> IDFBlocks;
1441 IDFs.calculate(IDFBlocks);
1442
1443 // Now place MemoryPhi nodes.
1444 for (auto &BB : IDFBlocks) {
1445 // Insert phi node
Daniel Berlinada263d2016-06-20 20:21:33 +00001446 AccessList *Accesses = getOrCreateAccessList(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001447 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001448 ValueToMemoryAccess[BB] = Phi;
George Burgess IVe1100f52016-02-02 22:46:49 +00001449 // Phi's always are placed at the front of the block.
1450 Accesses->push_front(Phi);
1451 }
1452
1453 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1454 // filled in with all blocks.
1455 SmallPtrSet<BasicBlock *, 16> Visited;
1456 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1457
George Burgess IV5f308972016-07-19 01:29:15 +00001458 CachingWalker *Walker = getWalkerImpl();
1459
1460 // We're doing a batch of updates; don't drop useful caches between them.
1461 Walker->setAutoResetWalker(false);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001462 OptimizeUses(this, Walker, AA, DT).optimizeUses();
George Burgess IV5f308972016-07-19 01:29:15 +00001463 Walker->setAutoResetWalker(true);
1464 Walker->resetClobberWalker();
1465
George Burgess IVe1100f52016-02-02 22:46:49 +00001466 // Mark the uses in unreachable blocks as live on entry, so that they go
1467 // somewhere.
1468 for (auto &BB : F)
1469 if (!Visited.count(&BB))
1470 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001471}
George Burgess IVe1100f52016-02-02 22:46:49 +00001472
George Burgess IV5f308972016-07-19 01:29:15 +00001473MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1474
1475MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001476 if (Walker)
1477 return Walker.get();
1478
1479 Walker = make_unique<CachingWalker>(this, AA, DT);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001480 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001481}
1482
Daniel Berlin14300262016-06-21 18:39:20 +00001483MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1484 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
1485 AccessList *Accesses = getOrCreateAccessList(BB);
1486 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001487 ValueToMemoryAccess[BB] = Phi;
Daniel Berlin14300262016-06-21 18:39:20 +00001488 // Phi's always are placed at the front of the block.
1489 Accesses->push_front(Phi);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001490 BlockNumberingValid.erase(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001491 return Phi;
1492}
1493
1494MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
1495 MemoryAccess *Definition) {
1496 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1497 MemoryUseOrDef *NewAccess = createNewAccess(I);
1498 assert(
1499 NewAccess != nullptr &&
1500 "Tried to create a memory access for a non-memory touching instruction");
1501 NewAccess->setDefiningAccess(Definition);
1502 return NewAccess;
1503}
1504
1505MemoryAccess *MemorySSA::createMemoryAccessInBB(Instruction *I,
1506 MemoryAccess *Definition,
1507 const BasicBlock *BB,
1508 InsertionPlace Point) {
1509 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1510 auto *Accesses = getOrCreateAccessList(BB);
1511 if (Point == Beginning) {
1512 // It goes after any phi nodes
1513 auto AI = std::find_if(
1514 Accesses->begin(), Accesses->end(),
1515 [](const MemoryAccess &MA) { return !isa<MemoryPhi>(MA); });
1516
1517 Accesses->insert(AI, NewAccess);
1518 } else {
1519 Accesses->push_back(NewAccess);
1520 }
Daniel Berlin5c46b942016-07-19 22:49:43 +00001521 BlockNumberingValid.erase(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001522 return NewAccess;
1523}
1524MemoryAccess *MemorySSA::createMemoryAccessBefore(Instruction *I,
1525 MemoryAccess *Definition,
1526 MemoryAccess *InsertPt) {
1527 assert(I->getParent() == InsertPt->getBlock() &&
1528 "New and old access must be in the same block");
1529 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1530 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
1531 Accesses->insert(AccessList::iterator(InsertPt), NewAccess);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001532 BlockNumberingValid.erase(InsertPt->getBlock());
Daniel Berlin14300262016-06-21 18:39:20 +00001533 return NewAccess;
1534}
1535
1536MemoryAccess *MemorySSA::createMemoryAccessAfter(Instruction *I,
1537 MemoryAccess *Definition,
1538 MemoryAccess *InsertPt) {
1539 assert(I->getParent() == InsertPt->getBlock() &&
1540 "New and old access must be in the same block");
1541 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1542 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
1543 Accesses->insertAfter(AccessList::iterator(InsertPt), NewAccess);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001544 BlockNumberingValid.erase(InsertPt->getBlock());
Daniel Berlin14300262016-06-21 18:39:20 +00001545 return NewAccess;
1546}
1547
George Burgess IVe1100f52016-02-02 22:46:49 +00001548/// \brief Helper function to create new memory accesses
Peter Collingbourneffecb142016-05-26 01:19:17 +00001549MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001550 // The assume intrinsic has a control dependency which we model by claiming
1551 // that it writes arbitrarily. Ignore that fake memory dependency here.
1552 // FIXME: Replace this special casing with a more accurate modelling of
1553 // assume's control dependency.
1554 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1555 if (II->getIntrinsicID() == Intrinsic::assume)
1556 return nullptr;
1557
George Burgess IVe1100f52016-02-02 22:46:49 +00001558 // Find out what affect this instruction has on memory.
1559 ModRefInfo ModRef = AA->getModRefInfo(I);
1560 bool Def = bool(ModRef & MRI_Mod);
1561 bool Use = bool(ModRef & MRI_Ref);
1562
1563 // It's possible for an instruction to not modify memory at all. During
1564 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +00001565 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +00001566 return nullptr;
1567
1568 assert((Def || Use) &&
1569 "Trying to create a memory access with a non-memory instruction");
1570
George Burgess IVb42b7622016-03-11 19:34:03 +00001571 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001572 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +00001573 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +00001574 else
George Burgess IVb42b7622016-03-11 19:34:03 +00001575 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
Daniel Berlin5130cc82016-07-31 21:08:20 +00001576 ValueToMemoryAccess[I] = MUD;
George Burgess IVb42b7622016-03-11 19:34:03 +00001577 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001578}
1579
1580MemoryAccess *MemorySSA::findDominatingDef(BasicBlock *UseBlock,
1581 enum InsertionPlace Where) {
1582 // Handle the initial case
1583 if (Where == Beginning)
1584 // The only thing that could define us at the beginning is a phi node
1585 if (MemoryPhi *Phi = getMemoryAccess(UseBlock))
1586 return Phi;
1587
1588 DomTreeNode *CurrNode = DT->getNode(UseBlock);
1589 // Need to be defined by our dominator
1590 if (Where == Beginning)
1591 CurrNode = CurrNode->getIDom();
1592 Where = End;
1593 while (CurrNode) {
1594 auto It = PerBlockAccesses.find(CurrNode->getBlock());
1595 if (It != PerBlockAccesses.end()) {
1596 auto &Accesses = It->second;
David Majnemerd7708772016-06-24 04:05:21 +00001597 for (MemoryAccess &RA : reverse(*Accesses)) {
1598 if (isa<MemoryDef>(RA) || isa<MemoryPhi>(RA))
1599 return &RA;
George Burgess IVe1100f52016-02-02 22:46:49 +00001600 }
1601 }
1602 CurrNode = CurrNode->getIDom();
1603 }
1604 return LiveOnEntryDef.get();
1605}
1606
1607/// \brief Returns true if \p Replacer dominates \p Replacee .
1608bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1609 const MemoryAccess *Replacee) const {
1610 if (isa<MemoryUseOrDef>(Replacee))
1611 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1612 const auto *MP = cast<MemoryPhi>(Replacee);
1613 // For a phi node, the use occurs in the predecessor block of the phi node.
1614 // Since we may occur multiple times in the phi node, we have to check each
1615 // operand to ensure Replacer dominates each operand where Replacee occurs.
1616 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +00001617 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +00001618 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1619 return false;
1620 }
1621 return true;
1622}
1623
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001624/// \brief If all arguments of a MemoryPHI are defined by the same incoming
1625/// argument, return that argument.
1626static MemoryAccess *onlySingleValue(MemoryPhi *MP) {
1627 MemoryAccess *MA = nullptr;
1628
1629 for (auto &Arg : MP->operands()) {
1630 if (!MA)
1631 MA = cast<MemoryAccess>(Arg);
1632 else if (MA != Arg)
1633 return nullptr;
1634 }
1635 return MA;
1636}
1637
1638/// \brief Properly remove \p MA from all of MemorySSA's lookup tables.
1639///
1640/// Because of the way the intrusive list and use lists work, it is important to
1641/// do removal in the right order.
1642void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1643 assert(MA->use_empty() &&
1644 "Trying to remove memory access that still has uses");
Daniel Berlin5c46b942016-07-19 22:49:43 +00001645 BlockNumbering.erase(MA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001646 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
1647 MUD->setDefiningAccess(nullptr);
1648 // Invalidate our walker's cache if necessary
1649 if (!isa<MemoryUse>(MA))
1650 Walker->invalidateInfo(MA);
1651 // The call below to erase will destroy MA, so we can't change the order we
1652 // are doing things here
1653 Value *MemoryInst;
1654 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1655 MemoryInst = MUD->getMemoryInst();
1656 } else {
1657 MemoryInst = MA->getBlock();
1658 }
Daniel Berlin5130cc82016-07-31 21:08:20 +00001659 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1660 if (VMA->second == MA)
1661 ValueToMemoryAccess.erase(VMA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001662
George Burgess IVe0e6e482016-03-02 02:35:04 +00001663 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
Daniel Berlinada263d2016-06-20 20:21:33 +00001664 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001665 Accesses->erase(MA);
George Burgess IVe0e6e482016-03-02 02:35:04 +00001666 if (Accesses->empty())
1667 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001668}
1669
1670void MemorySSA::removeMemoryAccess(MemoryAccess *MA) {
1671 assert(!isLiveOnEntryDef(MA) && "Trying to remove the live on entry def");
1672 // We can only delete phi nodes if they have no uses, or we can replace all
1673 // uses with a single definition.
1674 MemoryAccess *NewDefTarget = nullptr;
1675 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) {
1676 // Note that it is sufficient to know that all edges of the phi node have
1677 // the same argument. If they do, by the definition of dominance frontiers
1678 // (which we used to place this phi), that argument must dominate this phi,
1679 // and thus, must dominate the phi's uses, and so we will not hit the assert
1680 // below.
1681 NewDefTarget = onlySingleValue(MP);
1682 assert((NewDefTarget || MP->use_empty()) &&
1683 "We can't delete this memory phi");
1684 } else {
1685 NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
1686 }
1687
1688 // Re-point the uses at our defining access
1689 if (!MA->use_empty())
1690 MA->replaceAllUsesWith(NewDefTarget);
1691
1692 // The call below to erase will destroy MA, so we can't change the order we
1693 // are doing things here
1694 removeFromLookups(MA);
1695}
1696
George Burgess IVe1100f52016-02-02 22:46:49 +00001697void MemorySSA::print(raw_ostream &OS) const {
1698 MemorySSAAnnotatedWriter Writer(this);
1699 F.print(OS, &Writer);
1700}
1701
1702void MemorySSA::dump() const {
1703 MemorySSAAnnotatedWriter Writer(this);
1704 F.print(dbgs(), &Writer);
1705}
1706
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001707void MemorySSA::verifyMemorySSA() const {
1708 verifyDefUses(F);
1709 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001710 verifyOrdering(F);
1711}
1712
1713/// \brief Verify that the order and existence of MemoryAccesses matches the
1714/// order and existence of memory affecting instructions.
1715void MemorySSA::verifyOrdering(Function &F) const {
1716 // Walk all the blocks, comparing what the lookups think and what the access
1717 // lists think, as well as the order in the blocks vs the order in the access
1718 // lists.
1719 SmallVector<MemoryAccess *, 32> ActualAccesses;
1720 for (BasicBlock &B : F) {
1721 const AccessList *AL = getBlockAccesses(&B);
1722 MemoryAccess *Phi = getMemoryAccess(&B);
1723 if (Phi)
1724 ActualAccesses.push_back(Phi);
1725 for (Instruction &I : B) {
1726 MemoryAccess *MA = getMemoryAccess(&I);
1727 assert((!MA || AL) && "We have memory affecting instructions "
1728 "in this block but they are not in the "
1729 "access list");
1730 if (MA)
1731 ActualAccesses.push_back(MA);
1732 }
1733 // Either we hit the assert, really have no accesses, or we have both
1734 // accesses and an access list
1735 if (!AL)
1736 continue;
1737 assert(AL->size() == ActualAccesses.size() &&
1738 "We don't have the same number of accesses in the block as on the "
1739 "access list");
1740 auto ALI = AL->begin();
1741 auto AAI = ActualAccesses.begin();
1742 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1743 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1744 ++ALI;
1745 ++AAI;
1746 }
1747 ActualAccesses.clear();
1748 }
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001749}
1750
George Burgess IVe1100f52016-02-02 22:46:49 +00001751/// \brief Verify the domination properties of MemorySSA by checking that each
1752/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001753void MemorySSA::verifyDomination(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001754 for (BasicBlock &B : F) {
1755 // Phi nodes are attached to basic blocks
1756 if (MemoryPhi *MP = getMemoryAccess(&B)) {
1757 for (User *U : MP->users()) {
1758 BasicBlock *UseBlock;
1759 // Phi operands are used on edges, we simulate the right domination by
1760 // acting as if the use occurred at the end of the predecessor block.
1761 if (MemoryPhi *P = dyn_cast<MemoryPhi>(U)) {
1762 for (const auto &Arg : P->operands()) {
1763 if (Arg == MP) {
1764 UseBlock = P->getIncomingBlock(Arg);
1765 break;
1766 }
1767 }
1768 } else {
1769 UseBlock = cast<MemoryAccess>(U)->getBlock();
1770 }
George Burgess IV60adac42016-02-02 23:26:01 +00001771 (void)UseBlock;
George Burgess IVe1100f52016-02-02 22:46:49 +00001772 assert(DT->dominates(MP->getBlock(), UseBlock) &&
1773 "Memory PHI does not dominate it's uses");
1774 }
1775 }
1776
1777 for (Instruction &I : B) {
1778 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
1779 if (!MD)
1780 continue;
1781
Benjamin Kramer451f54c2016-02-22 13:11:58 +00001782 for (User *U : MD->users()) {
Daniel Berlinada263d2016-06-20 20:21:33 +00001783 BasicBlock *UseBlock;
1784 (void)UseBlock;
George Burgess IVe1100f52016-02-02 22:46:49 +00001785 // Things are allowed to flow to phi nodes over their predecessor edge.
1786 if (auto *P = dyn_cast<MemoryPhi>(U)) {
1787 for (const auto &Arg : P->operands()) {
1788 if (Arg == MD) {
1789 UseBlock = P->getIncomingBlock(Arg);
1790 break;
1791 }
1792 }
1793 } else {
1794 UseBlock = cast<MemoryAccess>(U)->getBlock();
1795 }
1796 assert(DT->dominates(MD->getBlock(), UseBlock) &&
1797 "Memory Def does not dominate it's uses");
1798 }
1799 }
1800 }
1801}
1802
1803/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
1804/// appears in the use list of \p Def.
1805///
1806/// llvm_unreachable is used instead of asserts because this may be called in
1807/// a build without asserts. In that case, we don't want this to turn into a
1808/// nop.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001809void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001810 // The live on entry use may cause us to get a NULL def here
1811 if (!Def) {
1812 if (!isLiveOnEntryDef(Use))
1813 llvm_unreachable("Null def but use not point to live on entry def");
1814 } else if (std::find(Def->user_begin(), Def->user_end(), Use) ==
1815 Def->user_end()) {
1816 llvm_unreachable("Did not find use in def's use list");
1817 }
1818}
1819
1820/// \brief Verify the immediate use information, by walking all the memory
1821/// accesses and verifying that, for each use, it appears in the
1822/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001823void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001824 for (BasicBlock &B : F) {
1825 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00001826 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00001827 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
1828 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00001829 "Incomplete MemoryPhi Node");
George Burgess IVe1100f52016-02-02 22:46:49 +00001830 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1831 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Daniel Berlin14300262016-06-21 18:39:20 +00001832 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001833
1834 for (Instruction &I : B) {
1835 if (MemoryAccess *MA = getMemoryAccess(&I)) {
1836 assert(isa<MemoryUseOrDef>(MA) &&
1837 "Found a phi node not attached to a bb");
1838 verifyUseInDefs(cast<MemoryUseOrDef>(MA)->getDefiningAccess(), MA);
1839 }
1840 }
1841 }
1842}
1843
1844MemoryAccess *MemorySSA::getMemoryAccess(const Value *I) const {
Daniel Berlinf6c9ae92016-02-10 17:41:25 +00001845 return ValueToMemoryAccess.lookup(I);
George Burgess IVe1100f52016-02-02 22:46:49 +00001846}
1847
1848MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
1849 return cast_or_null<MemoryPhi>(getMemoryAccess((const Value *)BB));
1850}
1851
Daniel Berlin5c46b942016-07-19 22:49:43 +00001852/// Perform a local numbering on blocks so that instruction ordering can be
1853/// determined in constant time.
1854/// TODO: We currently just number in order. If we numbered by N, we could
1855/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
1856/// log2(N) sequences of mixed before and after) without needing to invalidate
1857/// the numbering.
1858void MemorySSA::renumberBlock(const BasicBlock *B) const {
1859 // The pre-increment ensures the numbers really start at 1.
1860 unsigned long CurrentNumber = 0;
1861 const AccessList *AL = getBlockAccesses(B);
1862 assert(AL != nullptr && "Asking to renumber an empty block");
1863 for (const auto &I : *AL)
1864 BlockNumbering[&I] = ++CurrentNumber;
1865 BlockNumberingValid.insert(B);
1866}
1867
George Burgess IVe1100f52016-02-02 22:46:49 +00001868/// \brief Determine, for two memory accesses in the same block,
1869/// whether \p Dominator dominates \p Dominatee.
1870/// \returns True if \p Dominator dominates \p Dominatee.
1871bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
1872 const MemoryAccess *Dominatee) const {
Sebastian Pope1f60b12016-06-10 21:36:41 +00001873
Daniel Berlin5c46b942016-07-19 22:49:43 +00001874 const BasicBlock *DominatorBlock = Dominator->getBlock();
Daniel Berlin5c46b942016-07-19 22:49:43 +00001875
Daniel Berlin19860302016-07-19 23:08:08 +00001876 assert((DominatorBlock == Dominatee->getBlock()) &&
Daniel Berlin5c46b942016-07-19 22:49:43 +00001877 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00001878 // A node dominates itself.
1879 if (Dominatee == Dominator)
1880 return true;
1881
1882 // When Dominatee is defined on function entry, it is not dominated by another
1883 // memory access.
1884 if (isLiveOnEntryDef(Dominatee))
1885 return false;
1886
1887 // When Dominator is defined on function entry, it dominates the other memory
1888 // access.
1889 if (isLiveOnEntryDef(Dominator))
1890 return true;
1891
Daniel Berlin5c46b942016-07-19 22:49:43 +00001892 if (!BlockNumberingValid.count(DominatorBlock))
1893 renumberBlock(DominatorBlock);
George Burgess IVe1100f52016-02-02 22:46:49 +00001894
Daniel Berlin5c46b942016-07-19 22:49:43 +00001895 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
1896 // All numbers start with 1
1897 assert(DominatorNum != 0 && "Block was not numbered properly");
1898 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
1899 assert(DominateeNum != 0 && "Block was not numbered properly");
1900 return DominatorNum < DominateeNum;
George Burgess IVe1100f52016-02-02 22:46:49 +00001901}
1902
George Burgess IV5f308972016-07-19 01:29:15 +00001903bool MemorySSA::dominates(const MemoryAccess *Dominator,
1904 const MemoryAccess *Dominatee) const {
1905 if (Dominator == Dominatee)
1906 return true;
1907
1908 if (isLiveOnEntryDef(Dominatee))
1909 return false;
1910
1911 if (Dominator->getBlock() != Dominatee->getBlock())
1912 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
1913 return locallyDominates(Dominator, Dominatee);
1914}
1915
George Burgess IVe1100f52016-02-02 22:46:49 +00001916const static char LiveOnEntryStr[] = "liveOnEntry";
1917
1918void MemoryDef::print(raw_ostream &OS) const {
1919 MemoryAccess *UO = getDefiningAccess();
1920
1921 OS << getID() << " = MemoryDef(";
1922 if (UO && UO->getID())
1923 OS << UO->getID();
1924 else
1925 OS << LiveOnEntryStr;
1926 OS << ')';
1927}
1928
1929void MemoryPhi::print(raw_ostream &OS) const {
1930 bool First = true;
1931 OS << getID() << " = MemoryPhi(";
1932 for (const auto &Op : operands()) {
1933 BasicBlock *BB = getIncomingBlock(Op);
1934 MemoryAccess *MA = cast<MemoryAccess>(Op);
1935 if (!First)
1936 OS << ',';
1937 else
1938 First = false;
1939
1940 OS << '{';
1941 if (BB->hasName())
1942 OS << BB->getName();
1943 else
1944 BB->printAsOperand(OS, false);
1945 OS << ',';
1946 if (unsigned ID = MA->getID())
1947 OS << ID;
1948 else
1949 OS << LiveOnEntryStr;
1950 OS << '}';
1951 }
1952 OS << ')';
1953}
1954
1955MemoryAccess::~MemoryAccess() {}
1956
1957void MemoryUse::print(raw_ostream &OS) const {
1958 MemoryAccess *UO = getDefiningAccess();
1959 OS << "MemoryUse(";
1960 if (UO && UO->getID())
1961 OS << UO->getID();
1962 else
1963 OS << LiveOnEntryStr;
1964 OS << ')';
1965}
1966
1967void MemoryAccess::dump() const {
1968 print(dbgs());
1969 dbgs() << "\n";
1970}
1971
Chad Rosier232e29e2016-07-06 21:20:47 +00001972char MemorySSAPrinterLegacyPass::ID = 0;
1973
1974MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
1975 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
1976}
1977
1978void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
1979 AU.setPreservesAll();
1980 AU.addRequired<MemorySSAWrapperPass>();
1981 AU.addPreserved<MemorySSAWrapperPass>();
1982}
1983
1984bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
1985 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
1986 MSSA.print(dbgs());
1987 if (VerifyMemorySSA)
1988 MSSA.verifyMemorySSA();
1989 return false;
1990}
1991
Geoff Berryb96d3b22016-06-01 21:30:40 +00001992char MemorySSAAnalysis::PassID;
George Burgess IVe1100f52016-02-02 22:46:49 +00001993
Geoff Berryb96d3b22016-06-01 21:30:40 +00001994MemorySSA MemorySSAAnalysis::run(Function &F, AnalysisManager<Function> &AM) {
1995 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1996 auto &AA = AM.getResult<AAManager>(F);
1997 return MemorySSA(F, &AA, &DT);
George Burgess IVe1100f52016-02-02 22:46:49 +00001998}
1999
Geoff Berryb96d3b22016-06-01 21:30:40 +00002000PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
2001 FunctionAnalysisManager &AM) {
2002 OS << "MemorySSA for function: " << F.getName() << "\n";
2003 AM.getResult<MemorySSAAnalysis>(F).print(OS);
2004
2005 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00002006}
2007
Geoff Berryb96d3b22016-06-01 21:30:40 +00002008PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
2009 FunctionAnalysisManager &AM) {
2010 AM.getResult<MemorySSAAnalysis>(F).verifyMemorySSA();
2011
2012 return PreservedAnalyses::all();
2013}
2014
2015char MemorySSAWrapperPass::ID = 0;
2016
2017MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
2018 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
2019}
2020
2021void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
2022
2023void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002024 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002025 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
2026 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00002027}
2028
Geoff Berryb96d3b22016-06-01 21:30:40 +00002029bool MemorySSAWrapperPass::runOnFunction(Function &F) {
2030 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2031 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2032 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002033 return false;
2034}
2035
Geoff Berryb96d3b22016-06-01 21:30:40 +00002036void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00002037
Geoff Berryb96d3b22016-06-01 21:30:40 +00002038void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002039 MSSA->print(OS);
2040}
2041
George Burgess IVe1100f52016-02-02 22:46:49 +00002042MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
2043
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002044MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A,
2045 DominatorTree *D)
Daniel Berlin5c46b942016-07-19 22:49:43 +00002046 : MemorySSAWalker(M), Walker(*M, *A, *D, Cache), AutoResetWalker(true) {}
George Burgess IVe1100f52016-02-02 22:46:49 +00002047
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002048MemorySSA::CachingWalker::~CachingWalker() {}
George Burgess IVe1100f52016-02-02 22:46:49 +00002049
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002050void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) {
Daniel Berlin83fc77b2016-03-01 18:46:54 +00002051 // TODO: We can do much better cache invalidation with differently stored
2052 // caches. For now, for MemoryUses, we simply remove them
2053 // from the cache, and kill the entire call/non-call cache for everything
2054 // else. The problem is for phis or defs, currently we'd need to follow use
2055 // chains down and invalidate anything below us in the chain that currently
2056 // terminates at this access.
2057
2058 // See if this is a MemoryUse, if so, just remove the cached info. MemoryUse
2059 // is by definition never a barrier, so nothing in the cache could point to
2060 // this use. In that case, we only need invalidate the info for the use
2061 // itself.
2062
2063 if (MemoryUse *MU = dyn_cast<MemoryUse>(MA)) {
George Burgess IV5f308972016-07-19 01:29:15 +00002064 UpwardsMemoryQuery Q(MU->getMemoryInst(), MU);
2065 Cache.remove(MU, Q.StartingLoc, Q.IsCall);
Geoff Berry9fe26e62016-04-22 14:44:10 +00002066 } else {
2067 // 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 +00002068 Cache.clear();
Geoff Berry9fe26e62016-04-22 14:44:10 +00002069 }
2070
Filipe Cabecinhas0da99372016-04-29 15:22:48 +00002071#ifdef EXPENSIVE_CHECKS
Geoff Berry9fe26e62016-04-22 14:44:10 +00002072 verifyRemoved(MA);
2073#endif
Daniel Berlin83fc77b2016-03-01 18:46:54 +00002074}
2075
George Burgess IVe1100f52016-02-02 22:46:49 +00002076/// \brief Walk the use-def chains starting at \p MA and find
2077/// the MemoryAccess that actually clobbers Loc.
2078///
2079/// \returns our clobbering memory access
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002080MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
2081 MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +00002082 MemoryAccess *New = Walker.findClobber(StartingAccess, Q);
2083#ifdef EXPENSIVE_CHECKS
2084 MemoryAccess *NewNoCache =
2085 Walker.findClobber(StartingAccess, Q, /*UseWalkerCache=*/false);
2086 assert(NewNoCache == New && "Cache made us hand back a different result?");
2087#endif
2088 if (AutoResetWalker)
2089 resetClobberWalker();
2090 return New;
George Burgess IVe1100f52016-02-02 22:46:49 +00002091}
2092
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002093MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
2094 MemoryAccess *StartingAccess, MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002095 if (isa<MemoryPhi>(StartingAccess))
2096 return StartingAccess;
2097
2098 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
2099 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
2100 return StartingUseOrDef;
2101
2102 Instruction *I = StartingUseOrDef->getMemoryInst();
2103
2104 // Conservatively, fences are always clobbers, so don't perform the walk if we
2105 // hit a fence.
David Majnemera940f362016-07-15 17:19:24 +00002106 if (!ImmutableCallSite(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002107 return StartingUseOrDef;
2108
2109 UpwardsMemoryQuery Q;
2110 Q.OriginalAccess = StartingUseOrDef;
2111 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00002112 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00002113 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00002114
George Burgess IV5f308972016-07-19 01:29:15 +00002115 if (auto *CacheResult = Cache.lookup(StartingUseOrDef, Loc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00002116 return CacheResult;
2117
2118 // Unlike the other function, do not walk to the def of a def, because we are
2119 // handed something we already believe is the clobbering access.
2120 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
2121 ? StartingUseOrDef->getDefiningAccess()
2122 : StartingUseOrDef;
2123
2124 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002125 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2126 DEBUG(dbgs() << *StartingUseOrDef << "\n");
2127 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2128 DEBUG(dbgs() << *Clobber << "\n");
2129 return Clobber;
2130}
2131
2132MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002133MemorySSA::CachingWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
2134 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2135 // If this is a MemoryPhi, we can't do anything.
2136 if (!StartingAccess)
2137 return MA;
George Burgess IVe1100f52016-02-02 22:46:49 +00002138
George Burgess IV400ae402016-07-20 19:51:34 +00002139 const Instruction *I = StartingAccess->getMemoryInst();
George Burgess IV5f308972016-07-19 01:29:15 +00002140 UpwardsMemoryQuery Q(I, StartingAccess);
David Majnemera940f362016-07-15 17:19:24 +00002141 // We can't sanely do anything with a fences, they conservatively
George Burgess IVe1100f52016-02-02 22:46:49 +00002142 // clobber all memory, and have no locations to get pointers from to
David Majnemera940f362016-07-15 17:19:24 +00002143 // try to disambiguate.
George Burgess IV5f308972016-07-19 01:29:15 +00002144 if (!Q.IsCall && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002145 return StartingAccess;
2146
George Burgess IV5f308972016-07-19 01:29:15 +00002147 if (auto *CacheResult = Cache.lookup(StartingAccess, Q.StartingLoc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00002148 return CacheResult;
2149
2150 // Start with the thing we already think clobbers this location
2151 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2152
2153 // At this point, DefiningAccess may be the live on entry def.
2154 // If it is, we will not get a better result.
2155 if (MSSA->isLiveOnEntryDef(DefiningAccess))
2156 return DefiningAccess;
2157
2158 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002159 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2160 DEBUG(dbgs() << *DefiningAccess << "\n");
2161 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2162 DEBUG(dbgs() << *Result << "\n");
2163
2164 return Result;
2165}
2166
Geoff Berry9fe26e62016-04-22 14:44:10 +00002167// Verify that MA doesn't exist in any of the caches.
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002168void MemorySSA::CachingWalker::verifyRemoved(MemoryAccess *MA) {
George Burgess IV5f308972016-07-19 01:29:15 +00002169 assert(!Cache.contains(MA) && "Found removed MemoryAccess in cache.");
Geoff Berry9fe26e62016-04-22 14:44:10 +00002170}
2171
George Burgess IVe1100f52016-02-02 22:46:49 +00002172MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002173DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002174 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2175 return Use->getDefiningAccess();
2176 return MA;
2177}
2178
2179MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
2180 MemoryAccess *StartingAccess, MemoryLocation &) {
2181 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2182 return Use->getDefiningAccess();
2183 return StartingAccess;
2184}
George Burgess IV5f308972016-07-19 01:29:15 +00002185} // namespace llvm