blob: 289fff8292d31b25a852a807128ea6920bb1ae8d [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"
20#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/Analysis/CFG.h"
25#include "llvm/Analysis/GlobalsModRef.h"
26#include "llvm/Analysis/IteratedDominanceFrontier.h"
27#include "llvm/Analysis/MemoryLocation.h"
28#include "llvm/Analysis/PHITransAddr.h"
29#include "llvm/IR/AssemblyAnnotationWriter.h"
30#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/Dominators.h"
32#include "llvm/IR/GlobalVariable.h"
33#include "llvm/IR/IRBuilder.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/Metadata.h"
37#include "llvm/IR/Module.h"
38#include "llvm/IR/PatternMatch.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000039#include "llvm/Support/Debug.h"
40#include "llvm/Support/FormattedStream.h"
41#include "llvm/Transforms/Scalar.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000042#include <algorithm>
43
44#define DEBUG_TYPE "memoryssa"
45using namespace llvm;
46STATISTIC(NumClobberCacheLookups, "Number of Memory SSA version cache lookups");
47STATISTIC(NumClobberCacheHits, "Number of Memory SSA version cache hits");
48STATISTIC(NumClobberCacheInserts, "Number of MemorySSA version cache inserts");
Geoff Berryb96d3b22016-06-01 21:30:40 +000049
Geoff Berryefb0dd12016-06-14 21:19:40 +000050INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
Geoff Berryb96d3b22016-06-01 21:30:40 +000051 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000052INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
53INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Geoff Berryefb0dd12016-06-14 21:19:40 +000054INITIALIZE_PASS_END(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
55 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000056
57namespace llvm {
George Burgess IVe1100f52016-02-02 22:46:49 +000058/// \brief An assembly annotator class to print Memory SSA information in
59/// comments.
60class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
61 friend class MemorySSA;
62 const MemorySSA *MSSA;
63
64public:
65 MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
66
67 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
68 formatted_raw_ostream &OS) {
69 if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
70 OS << "; " << *MA << "\n";
71 }
72
73 virtual void emitInstructionAnnot(const Instruction *I,
74 formatted_raw_ostream &OS) {
75 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
76 OS << "; " << *MA << "\n";
77 }
78};
George Burgess IVfd1f2f82016-06-24 21:02:12 +000079
80/// \brief A MemorySSAWalker that does AA walks and caching of lookups to
81/// disambiguate accesses.
82///
83/// FIXME: The current implementation of this can take quadratic space in rare
84/// cases. This can be fixed, but it is something to note until it is fixed.
85///
86/// In order to trigger this behavior, you need to store to N distinct locations
87/// (that AA can prove don't alias), perform M stores to other memory
88/// locations that AA can prove don't alias any of the initial N locations, and
89/// then load from all of the N locations. In this case, we insert M cache
90/// entries for each of the N loads.
91///
92/// For example:
93/// define i32 @foo() {
94/// %a = alloca i32, align 4
95/// %b = alloca i32, align 4
96/// store i32 0, i32* %a, align 4
97/// store i32 0, i32* %b, align 4
98///
99/// ; Insert M stores to other memory that doesn't alias %a or %b here
100///
101/// %c = load i32, i32* %a, align 4 ; Caches M entries in
102/// ; CachedUpwardsClobberingAccess for the
103/// ; MemoryLocation %a
104/// %d = load i32, i32* %b, align 4 ; Caches M entries in
105/// ; CachedUpwardsClobberingAccess for the
106/// ; MemoryLocation %b
107///
108/// ; For completeness' sake, loading %a or %b again would not cache *another*
109/// ; M entries.
110/// %r = add i32 %c, %d
111/// ret i32 %r
112/// }
113class MemorySSA::CachingWalker final : public MemorySSAWalker {
114public:
115 CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *);
116 ~CachingWalker() override;
117
118 MemoryAccess *getClobberingMemoryAccess(const Instruction *) override;
119 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
120 MemoryLocation &) override;
121 void invalidateInfo(MemoryAccess *) override;
122
123protected:
124 struct UpwardsMemoryQuery;
125 MemoryAccess *doCacheLookup(const MemoryAccess *, const UpwardsMemoryQuery &,
126 const MemoryLocation &);
127
128 void doCacheInsert(const MemoryAccess *, MemoryAccess *,
129 const UpwardsMemoryQuery &, const MemoryLocation &);
130
131 void doCacheRemove(const MemoryAccess *, const UpwardsMemoryQuery &,
132 const MemoryLocation &);
133
134private:
135 MemoryAccessPair UpwardsDFSWalk(MemoryAccess *, const MemoryLocation &,
136 UpwardsMemoryQuery &, bool);
137 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, UpwardsMemoryQuery &);
138 bool instructionClobbersQuery(const MemoryDef *, UpwardsMemoryQuery &,
139 const MemoryLocation &Loc) const;
140 void verifyRemoved(MemoryAccess *);
141 SmallDenseMap<ConstMemoryAccessPair, MemoryAccess *>
142 CachedUpwardsClobberingAccess;
143 DenseMap<const MemoryAccess *, MemoryAccess *> CachedUpwardsClobberingCall;
144 AliasAnalysis *AA;
145 DominatorTree *DT;
146};
George Burgess IVe1100f52016-02-02 22:46:49 +0000147}
148
149namespace {
150struct RenamePassData {
151 DomTreeNode *DTN;
152 DomTreeNode::const_iterator ChildIt;
153 MemoryAccess *IncomingVal;
154
155 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
156 MemoryAccess *M)
157 : DTN(D), ChildIt(It), IncomingVal(M) {}
158 void swap(RenamePassData &RHS) {
159 std::swap(DTN, RHS.DTN);
160 std::swap(ChildIt, RHS.ChildIt);
161 std::swap(IncomingVal, RHS.IncomingVal);
162 }
163};
164}
165
166namespace llvm {
167/// \brief Rename a single basic block into MemorySSA form.
168/// Uses the standard SSA renaming algorithm.
169/// \returns The new incoming value.
170MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB,
171 MemoryAccess *IncomingVal) {
172 auto It = PerBlockAccesses.find(BB);
173 // Skip most processing if the list is empty.
174 if (It != PerBlockAccesses.end()) {
Daniel Berlinada263d2016-06-20 20:21:33 +0000175 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000176 for (MemoryAccess &L : *Accesses) {
177 switch (L.getValueID()) {
178 case Value::MemoryUseVal:
179 cast<MemoryUse>(&L)->setDefiningAccess(IncomingVal);
180 break;
181 case Value::MemoryDefVal:
182 // We can't legally optimize defs, because we only allow single
183 // memory phis/uses on operations, and if we optimize these, we can
184 // end up with multiple reaching defs. Uses do not have this
185 // problem, since they do not produce a value
186 cast<MemoryDef>(&L)->setDefiningAccess(IncomingVal);
187 IncomingVal = &L;
188 break;
189 case Value::MemoryPhiVal:
190 IncomingVal = &L;
191 break;
192 }
193 }
194 }
195
196 // Pass through values to our successors
197 for (const BasicBlock *S : successors(BB)) {
198 auto It = PerBlockAccesses.find(S);
199 // Rename the phi nodes in our successor block
200 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
201 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +0000202 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000203 auto *Phi = cast<MemoryPhi>(&Accesses->front());
204 assert(std::find(succ_begin(BB), succ_end(BB), S) != succ_end(BB) &&
205 "Must be at least one edge from Succ to BB!");
206 Phi->addIncoming(IncomingVal, BB);
207 }
208
209 return IncomingVal;
210}
211
212/// \brief This is the standard SSA renaming algorithm.
213///
214/// We walk the dominator tree in preorder, renaming accesses, and then filling
215/// in phi nodes in our successors.
216void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
217 SmallPtrSet<BasicBlock *, 16> &Visited) {
218 SmallVector<RenamePassData, 32> WorkStack;
219 IncomingVal = renameBlock(Root->getBlock(), IncomingVal);
220 WorkStack.push_back({Root, Root->begin(), IncomingVal});
221 Visited.insert(Root->getBlock());
222
223 while (!WorkStack.empty()) {
224 DomTreeNode *Node = WorkStack.back().DTN;
225 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
226 IncomingVal = WorkStack.back().IncomingVal;
227
228 if (ChildIt == Node->end()) {
229 WorkStack.pop_back();
230 } else {
231 DomTreeNode *Child = *ChildIt;
232 ++WorkStack.back().ChildIt;
233 BasicBlock *BB = Child->getBlock();
234 Visited.insert(BB);
235 IncomingVal = renameBlock(BB, IncomingVal);
236 WorkStack.push_back({Child, Child->begin(), IncomingVal});
237 }
238 }
239}
240
241/// \brief Compute dominator levels, used by the phi insertion algorithm above.
242void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) {
243 for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode());
244 DFI != DFE; ++DFI)
245 DomLevels[*DFI] = DFI.getPathLength() - 1;
246}
247
248/// \brief This handles unreachable block acccesses by deleting phi nodes in
249/// unreachable blocks, and marking all other unreachable MemoryAccess's as
250/// being uses of the live on entry definition.
251void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
252 assert(!DT->isReachableFromEntry(BB) &&
253 "Reachable block found while handling unreachable blocks");
254
255 auto It = PerBlockAccesses.find(BB);
256 if (It == PerBlockAccesses.end())
257 return;
258
259 auto &Accesses = It->second;
260 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
261 auto Next = std::next(AI);
262 // If we have a phi, just remove it. We are going to replace all
263 // users with live on entry.
264 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
265 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
266 else
267 Accesses->erase(AI);
268 AI = Next;
269 }
270}
271
Geoff Berryb96d3b22016-06-01 21:30:40 +0000272MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
273 : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
274 NextID(0) {
Daniel Berlin16ed57c2016-06-27 18:22:27 +0000275 buildMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +0000276}
277
278MemorySSA::MemorySSA(MemorySSA &&MSSA)
279 : AA(MSSA.AA), DT(MSSA.DT), F(MSSA.F),
280 ValueToMemoryAccess(std::move(MSSA.ValueToMemoryAccess)),
281 PerBlockAccesses(std::move(MSSA.PerBlockAccesses)),
282 LiveOnEntryDef(std::move(MSSA.LiveOnEntryDef)),
283 Walker(std::move(MSSA.Walker)), NextID(MSSA.NextID) {
284 // Update the Walker MSSA pointer so it doesn't point to the moved-from MSSA
285 // object any more.
286 Walker->MSSA = this;
287}
George Burgess IVe1100f52016-02-02 22:46:49 +0000288
289MemorySSA::~MemorySSA() {
290 // Drop all our references
291 for (const auto &Pair : PerBlockAccesses)
292 for (MemoryAccess &MA : *Pair.second)
293 MA.dropAllReferences();
294}
295
Daniel Berlin14300262016-06-21 18:39:20 +0000296MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +0000297 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
298
299 if (Res.second)
Daniel Berlinada263d2016-06-20 20:21:33 +0000300 Res.first->second = make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +0000301 return Res.first->second.get();
302}
303
Daniel Berlin16ed57c2016-06-27 18:22:27 +0000304void MemorySSA::buildMemorySSA() {
George Burgess IVe1100f52016-02-02 22:46:49 +0000305 // We create an access to represent "live on entry", for things like
306 // arguments or users of globals, where the memory they use is defined before
307 // the beginning of the function. We do not actually insert it into the IR.
308 // We do not define a live on exit for the immediate uses, and thus our
309 // semantics do *not* imply that something with no immediate uses can simply
310 // be removed.
311 BasicBlock &StartingPoint = F.getEntryBlock();
312 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
313 &StartingPoint, NextID++);
314
315 // We maintain lists of memory accesses per-block, trading memory for time. We
316 // could just look up the memory access for every possible instruction in the
317 // stream.
318 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
Daniel Berlin1b51a292016-02-07 01:52:19 +0000319 SmallPtrSet<BasicBlock *, 32> DefUseBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +0000320 // Go through each block, figure out where defs occur, and chain together all
321 // the accesses.
322 for (BasicBlock &B : F) {
Daniel Berlin7898ca62016-02-07 01:52:15 +0000323 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +0000324 AccessList *Accesses = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +0000325 for (Instruction &I : B) {
Peter Collingbourneffecb142016-05-26 01:19:17 +0000326 MemoryUseOrDef *MUD = createNewAccess(&I);
George Burgess IVb42b7622016-03-11 19:34:03 +0000327 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +0000328 continue;
George Burgess IV3887a412016-03-21 21:25:39 +0000329 InsertIntoDef |= isa<MemoryDef>(MUD);
Daniel Berlin1b51a292016-02-07 01:52:19 +0000330
George Burgess IVe1100f52016-02-02 22:46:49 +0000331 if (!Accesses)
332 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +0000333 Accesses->push_back(MUD);
George Burgess IVe1100f52016-02-02 22:46:49 +0000334 }
Daniel Berlin7898ca62016-02-07 01:52:15 +0000335 if (InsertIntoDef)
336 DefiningBlocks.insert(&B);
George Burgess IV3887a412016-03-21 21:25:39 +0000337 if (Accesses)
Daniel Berlin1b51a292016-02-07 01:52:19 +0000338 DefUseBlocks.insert(&B);
339 }
340
341 // Compute live-in.
342 // Live in is normally defined as "all the blocks on the path from each def to
343 // each of it's uses".
344 // MemoryDef's are implicit uses of previous state, so they are also uses.
345 // This means we don't really have def-only instructions. The only
346 // MemoryDef's that are not really uses are those that are of the LiveOnEntry
347 // variable (because LiveOnEntry can reach anywhere, and every def is a
348 // must-kill of LiveOnEntry).
349 // In theory, you could precisely compute live-in by using alias-analysis to
350 // disambiguate defs and uses to see which really pair up with which.
351 // In practice, this would be really expensive and difficult. So we simply
352 // assume all defs are also uses that need to be kept live.
353 // Because of this, the end result of this live-in computation will be "the
354 // entire set of basic blocks that reach any use".
355
356 SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
357 SmallVector<BasicBlock *, 64> LiveInBlockWorklist(DefUseBlocks.begin(),
358 DefUseBlocks.end());
359 // Now that we have a set of blocks where a value is live-in, recursively add
360 // predecessors until we find the full region the value is live.
361 while (!LiveInBlockWorklist.empty()) {
362 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
363
364 // The block really is live in here, insert it into the set. If already in
365 // the set, then it has already been processed.
366 if (!LiveInBlocks.insert(BB).second)
367 continue;
368
369 // Since the value is live into BB, it is either defined in a predecessor or
370 // live into it to.
371 LiveInBlockWorklist.append(pred_begin(BB), pred_end(BB));
George Burgess IVe1100f52016-02-02 22:46:49 +0000372 }
373
374 // Determine where our MemoryPhi's should go
Daniel Berlin77fa84e2016-04-19 06:13:28 +0000375 ForwardIDFCalculator IDFs(*DT);
George Burgess IVe1100f52016-02-02 22:46:49 +0000376 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin1b51a292016-02-07 01:52:19 +0000377 IDFs.setLiveInBlocks(LiveInBlocks);
George Burgess IVe1100f52016-02-02 22:46:49 +0000378 SmallVector<BasicBlock *, 32> IDFBlocks;
379 IDFs.calculate(IDFBlocks);
380
381 // Now place MemoryPhi nodes.
382 for (auto &BB : IDFBlocks) {
383 // Insert phi node
Daniel Berlinada263d2016-06-20 20:21:33 +0000384 AccessList *Accesses = getOrCreateAccessList(BB);
Daniel Berlin14300262016-06-21 18:39:20 +0000385 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlinf6c9ae92016-02-10 17:41:25 +0000386 ValueToMemoryAccess.insert(std::make_pair(BB, Phi));
George Burgess IVe1100f52016-02-02 22:46:49 +0000387 // Phi's always are placed at the front of the block.
388 Accesses->push_front(Phi);
389 }
390
391 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
392 // filled in with all blocks.
393 SmallPtrSet<BasicBlock *, 16> Visited;
394 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
395
Daniel Berlin16ed57c2016-06-27 18:22:27 +0000396 MemorySSAWalker *Walker = getWalker();
397
George Burgess IVe1100f52016-02-02 22:46:49 +0000398 // Now optimize the MemoryUse's defining access to point to the nearest
399 // dominating clobbering def.
400 // This ensures that MemoryUse's that are killed by the same store are
401 // immediate users of that store, one of the invariants we guarantee.
402 for (auto DomNode : depth_first(DT)) {
403 BasicBlock *BB = DomNode->getBlock();
404 auto AI = PerBlockAccesses.find(BB);
405 if (AI == PerBlockAccesses.end())
406 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +0000407 AccessList *Accesses = AI->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000408 for (auto &MA : *Accesses) {
409 if (auto *MU = dyn_cast<MemoryUse>(&MA)) {
410 Instruction *Inst = MU->getMemoryInst();
Daniel Berlin64120022016-03-02 21:16:28 +0000411 MU->setDefiningAccess(Walker->getClobberingMemoryAccess(Inst));
George Burgess IVe1100f52016-02-02 22:46:49 +0000412 }
413 }
414 }
415
416 // Mark the uses in unreachable blocks as live on entry, so that they go
417 // somewhere.
418 for (auto &BB : F)
419 if (!Visited.count(&BB))
420 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +0000421}
George Burgess IVe1100f52016-02-02 22:46:49 +0000422
Daniel Berlin16ed57c2016-06-27 18:22:27 +0000423MemorySSAWalker *MemorySSA::getWalker() {
424 if (Walker)
425 return Walker.get();
426
427 Walker = make_unique<CachingWalker>(this, AA, DT);
Geoff Berryb96d3b22016-06-01 21:30:40 +0000428 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000429}
430
Daniel Berlin14300262016-06-21 18:39:20 +0000431MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
432 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
433 AccessList *Accesses = getOrCreateAccessList(BB);
434 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
435 ValueToMemoryAccess.insert(std::make_pair(BB, Phi));
436 // Phi's always are placed at the front of the block.
437 Accesses->push_front(Phi);
438 return Phi;
439}
440
441MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
442 MemoryAccess *Definition) {
443 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
444 MemoryUseOrDef *NewAccess = createNewAccess(I);
445 assert(
446 NewAccess != nullptr &&
447 "Tried to create a memory access for a non-memory touching instruction");
448 NewAccess->setDefiningAccess(Definition);
449 return NewAccess;
450}
451
452MemoryAccess *MemorySSA::createMemoryAccessInBB(Instruction *I,
453 MemoryAccess *Definition,
454 const BasicBlock *BB,
455 InsertionPlace Point) {
456 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
457 auto *Accesses = getOrCreateAccessList(BB);
458 if (Point == Beginning) {
459 // It goes after any phi nodes
460 auto AI = std::find_if(
461 Accesses->begin(), Accesses->end(),
462 [](const MemoryAccess &MA) { return !isa<MemoryPhi>(MA); });
463
464 Accesses->insert(AI, NewAccess);
465 } else {
466 Accesses->push_back(NewAccess);
467 }
468
469 return NewAccess;
470}
471MemoryAccess *MemorySSA::createMemoryAccessBefore(Instruction *I,
472 MemoryAccess *Definition,
473 MemoryAccess *InsertPt) {
474 assert(I->getParent() == InsertPt->getBlock() &&
475 "New and old access must be in the same block");
476 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
477 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
478 Accesses->insert(AccessList::iterator(InsertPt), NewAccess);
479 return NewAccess;
480}
481
482MemoryAccess *MemorySSA::createMemoryAccessAfter(Instruction *I,
483 MemoryAccess *Definition,
484 MemoryAccess *InsertPt) {
485 assert(I->getParent() == InsertPt->getBlock() &&
486 "New and old access must be in the same block");
487 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
488 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
489 Accesses->insertAfter(AccessList::iterator(InsertPt), NewAccess);
490 return NewAccess;
491}
492
George Burgess IVe1100f52016-02-02 22:46:49 +0000493/// \brief Helper function to create new memory accesses
Peter Collingbourneffecb142016-05-26 01:19:17 +0000494MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +0000495 // The assume intrinsic has a control dependency which we model by claiming
496 // that it writes arbitrarily. Ignore that fake memory dependency here.
497 // FIXME: Replace this special casing with a more accurate modelling of
498 // assume's control dependency.
499 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
500 if (II->getIntrinsicID() == Intrinsic::assume)
501 return nullptr;
502
George Burgess IVe1100f52016-02-02 22:46:49 +0000503 // Find out what affect this instruction has on memory.
504 ModRefInfo ModRef = AA->getModRefInfo(I);
505 bool Def = bool(ModRef & MRI_Mod);
506 bool Use = bool(ModRef & MRI_Ref);
507
508 // It's possible for an instruction to not modify memory at all. During
509 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +0000510 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +0000511 return nullptr;
512
513 assert((Def || Use) &&
514 "Trying to create a memory access with a non-memory instruction");
515
George Burgess IVb42b7622016-03-11 19:34:03 +0000516 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +0000517 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +0000518 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +0000519 else
George Burgess IVb42b7622016-03-11 19:34:03 +0000520 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
521 ValueToMemoryAccess.insert(std::make_pair(I, MUD));
522 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +0000523}
524
525MemoryAccess *MemorySSA::findDominatingDef(BasicBlock *UseBlock,
526 enum InsertionPlace Where) {
527 // Handle the initial case
528 if (Where == Beginning)
529 // The only thing that could define us at the beginning is a phi node
530 if (MemoryPhi *Phi = getMemoryAccess(UseBlock))
531 return Phi;
532
533 DomTreeNode *CurrNode = DT->getNode(UseBlock);
534 // Need to be defined by our dominator
535 if (Where == Beginning)
536 CurrNode = CurrNode->getIDom();
537 Where = End;
538 while (CurrNode) {
539 auto It = PerBlockAccesses.find(CurrNode->getBlock());
540 if (It != PerBlockAccesses.end()) {
541 auto &Accesses = It->second;
David Majnemerd7708772016-06-24 04:05:21 +0000542 for (MemoryAccess &RA : reverse(*Accesses)) {
543 if (isa<MemoryDef>(RA) || isa<MemoryPhi>(RA))
544 return &RA;
George Burgess IVe1100f52016-02-02 22:46:49 +0000545 }
546 }
547 CurrNode = CurrNode->getIDom();
548 }
549 return LiveOnEntryDef.get();
550}
551
552/// \brief Returns true if \p Replacer dominates \p Replacee .
553bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
554 const MemoryAccess *Replacee) const {
555 if (isa<MemoryUseOrDef>(Replacee))
556 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
557 const auto *MP = cast<MemoryPhi>(Replacee);
558 // For a phi node, the use occurs in the predecessor block of the phi node.
559 // Since we may occur multiple times in the phi node, we have to check each
560 // operand to ensure Replacer dominates each operand where Replacee occurs.
561 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +0000562 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +0000563 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
564 return false;
565 }
566 return true;
567}
568
Daniel Berlin83fc77b2016-03-01 18:46:54 +0000569/// \brief If all arguments of a MemoryPHI are defined by the same incoming
570/// argument, return that argument.
571static MemoryAccess *onlySingleValue(MemoryPhi *MP) {
572 MemoryAccess *MA = nullptr;
573
574 for (auto &Arg : MP->operands()) {
575 if (!MA)
576 MA = cast<MemoryAccess>(Arg);
577 else if (MA != Arg)
578 return nullptr;
579 }
580 return MA;
581}
582
583/// \brief Properly remove \p MA from all of MemorySSA's lookup tables.
584///
585/// Because of the way the intrusive list and use lists work, it is important to
586/// do removal in the right order.
587void MemorySSA::removeFromLookups(MemoryAccess *MA) {
588 assert(MA->use_empty() &&
589 "Trying to remove memory access that still has uses");
590 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
591 MUD->setDefiningAccess(nullptr);
592 // Invalidate our walker's cache if necessary
593 if (!isa<MemoryUse>(MA))
594 Walker->invalidateInfo(MA);
595 // The call below to erase will destroy MA, so we can't change the order we
596 // are doing things here
597 Value *MemoryInst;
598 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
599 MemoryInst = MUD->getMemoryInst();
600 } else {
601 MemoryInst = MA->getBlock();
602 }
603 ValueToMemoryAccess.erase(MemoryInst);
604
George Burgess IVe0e6e482016-03-02 02:35:04 +0000605 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
Daniel Berlinada263d2016-06-20 20:21:33 +0000606 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin83fc77b2016-03-01 18:46:54 +0000607 Accesses->erase(MA);
George Burgess IVe0e6e482016-03-02 02:35:04 +0000608 if (Accesses->empty())
609 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +0000610}
611
612void MemorySSA::removeMemoryAccess(MemoryAccess *MA) {
613 assert(!isLiveOnEntryDef(MA) && "Trying to remove the live on entry def");
614 // We can only delete phi nodes if they have no uses, or we can replace all
615 // uses with a single definition.
616 MemoryAccess *NewDefTarget = nullptr;
617 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) {
618 // Note that it is sufficient to know that all edges of the phi node have
619 // the same argument. If they do, by the definition of dominance frontiers
620 // (which we used to place this phi), that argument must dominate this phi,
621 // and thus, must dominate the phi's uses, and so we will not hit the assert
622 // below.
623 NewDefTarget = onlySingleValue(MP);
624 assert((NewDefTarget || MP->use_empty()) &&
625 "We can't delete this memory phi");
626 } else {
627 NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
628 }
629
630 // Re-point the uses at our defining access
631 if (!MA->use_empty())
632 MA->replaceAllUsesWith(NewDefTarget);
633
634 // The call below to erase will destroy MA, so we can't change the order we
635 // are doing things here
636 removeFromLookups(MA);
637}
638
George Burgess IVe1100f52016-02-02 22:46:49 +0000639void MemorySSA::print(raw_ostream &OS) const {
640 MemorySSAAnnotatedWriter Writer(this);
641 F.print(OS, &Writer);
642}
643
644void MemorySSA::dump() const {
645 MemorySSAAnnotatedWriter Writer(this);
646 F.print(dbgs(), &Writer);
647}
648
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000649void MemorySSA::verifyMemorySSA() const {
650 verifyDefUses(F);
651 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +0000652 verifyOrdering(F);
653}
654
655/// \brief Verify that the order and existence of MemoryAccesses matches the
656/// order and existence of memory affecting instructions.
657void MemorySSA::verifyOrdering(Function &F) const {
658 // Walk all the blocks, comparing what the lookups think and what the access
659 // lists think, as well as the order in the blocks vs the order in the access
660 // lists.
661 SmallVector<MemoryAccess *, 32> ActualAccesses;
662 for (BasicBlock &B : F) {
663 const AccessList *AL = getBlockAccesses(&B);
664 MemoryAccess *Phi = getMemoryAccess(&B);
665 if (Phi)
666 ActualAccesses.push_back(Phi);
667 for (Instruction &I : B) {
668 MemoryAccess *MA = getMemoryAccess(&I);
669 assert((!MA || AL) && "We have memory affecting instructions "
670 "in this block but they are not in the "
671 "access list");
672 if (MA)
673 ActualAccesses.push_back(MA);
674 }
675 // Either we hit the assert, really have no accesses, or we have both
676 // accesses and an access list
677 if (!AL)
678 continue;
679 assert(AL->size() == ActualAccesses.size() &&
680 "We don't have the same number of accesses in the block as on the "
681 "access list");
682 auto ALI = AL->begin();
683 auto AAI = ActualAccesses.begin();
684 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
685 assert(&*ALI == *AAI && "Not the same accesses in the same order");
686 ++ALI;
687 ++AAI;
688 }
689 ActualAccesses.clear();
690 }
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000691}
692
George Burgess IVe1100f52016-02-02 22:46:49 +0000693/// \brief Verify the domination properties of MemorySSA by checking that each
694/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000695void MemorySSA::verifyDomination(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +0000696 for (BasicBlock &B : F) {
697 // Phi nodes are attached to basic blocks
698 if (MemoryPhi *MP = getMemoryAccess(&B)) {
699 for (User *U : MP->users()) {
700 BasicBlock *UseBlock;
701 // Phi operands are used on edges, we simulate the right domination by
702 // acting as if the use occurred at the end of the predecessor block.
703 if (MemoryPhi *P = dyn_cast<MemoryPhi>(U)) {
704 for (const auto &Arg : P->operands()) {
705 if (Arg == MP) {
706 UseBlock = P->getIncomingBlock(Arg);
707 break;
708 }
709 }
710 } else {
711 UseBlock = cast<MemoryAccess>(U)->getBlock();
712 }
George Burgess IV60adac42016-02-02 23:26:01 +0000713 (void)UseBlock;
George Burgess IVe1100f52016-02-02 22:46:49 +0000714 assert(DT->dominates(MP->getBlock(), UseBlock) &&
715 "Memory PHI does not dominate it's uses");
716 }
717 }
718
719 for (Instruction &I : B) {
720 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
721 if (!MD)
722 continue;
723
Benjamin Kramer451f54c2016-02-22 13:11:58 +0000724 for (User *U : MD->users()) {
Daniel Berlinada263d2016-06-20 20:21:33 +0000725 BasicBlock *UseBlock;
726 (void)UseBlock;
George Burgess IVe1100f52016-02-02 22:46:49 +0000727 // Things are allowed to flow to phi nodes over their predecessor edge.
728 if (auto *P = dyn_cast<MemoryPhi>(U)) {
729 for (const auto &Arg : P->operands()) {
730 if (Arg == MD) {
731 UseBlock = P->getIncomingBlock(Arg);
732 break;
733 }
734 }
735 } else {
736 UseBlock = cast<MemoryAccess>(U)->getBlock();
737 }
738 assert(DT->dominates(MD->getBlock(), UseBlock) &&
739 "Memory Def does not dominate it's uses");
740 }
741 }
742 }
743}
744
745/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
746/// appears in the use list of \p Def.
747///
748/// llvm_unreachable is used instead of asserts because this may be called in
749/// a build without asserts. In that case, we don't want this to turn into a
750/// nop.
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000751void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
George Burgess IVe1100f52016-02-02 22:46:49 +0000752 // The live on entry use may cause us to get a NULL def here
753 if (!Def) {
754 if (!isLiveOnEntryDef(Use))
755 llvm_unreachable("Null def but use not point to live on entry def");
756 } else if (std::find(Def->user_begin(), Def->user_end(), Use) ==
757 Def->user_end()) {
758 llvm_unreachable("Did not find use in def's use list");
759 }
760}
761
762/// \brief Verify the immediate use information, by walking all the memory
763/// accesses and verifying that, for each use, it appears in the
764/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000765void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +0000766 for (BasicBlock &B : F) {
767 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +0000768 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +0000769 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
770 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +0000771 "Incomplete MemoryPhi Node");
George Burgess IVe1100f52016-02-02 22:46:49 +0000772 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
773 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Daniel Berlin14300262016-06-21 18:39:20 +0000774 }
George Burgess IVe1100f52016-02-02 22:46:49 +0000775
776 for (Instruction &I : B) {
777 if (MemoryAccess *MA = getMemoryAccess(&I)) {
778 assert(isa<MemoryUseOrDef>(MA) &&
779 "Found a phi node not attached to a bb");
780 verifyUseInDefs(cast<MemoryUseOrDef>(MA)->getDefiningAccess(), MA);
781 }
782 }
783 }
784}
785
786MemoryAccess *MemorySSA::getMemoryAccess(const Value *I) const {
Daniel Berlinf6c9ae92016-02-10 17:41:25 +0000787 return ValueToMemoryAccess.lookup(I);
George Burgess IVe1100f52016-02-02 22:46:49 +0000788}
789
790MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
791 return cast_or_null<MemoryPhi>(getMemoryAccess((const Value *)BB));
792}
793
794/// \brief Determine, for two memory accesses in the same block,
795/// whether \p Dominator dominates \p Dominatee.
796/// \returns True if \p Dominator dominates \p Dominatee.
797bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
798 const MemoryAccess *Dominatee) const {
799
800 assert((Dominator->getBlock() == Dominatee->getBlock()) &&
801 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +0000802
803 // A node dominates itself.
804 if (Dominatee == Dominator)
805 return true;
806
807 // When Dominatee is defined on function entry, it is not dominated by another
808 // memory access.
809 if (isLiveOnEntryDef(Dominatee))
810 return false;
811
812 // When Dominator is defined on function entry, it dominates the other memory
813 // access.
814 if (isLiveOnEntryDef(Dominator))
815 return true;
816
George Burgess IVe1100f52016-02-02 22:46:49 +0000817 // Get the access list for the block
Daniel Berlinada263d2016-06-20 20:21:33 +0000818 const AccessList *AccessList = getBlockAccesses(Dominator->getBlock());
819 AccessList::const_reverse_iterator It(Dominator->getIterator());
George Burgess IVe1100f52016-02-02 22:46:49 +0000820
821 // If we hit the beginning of the access list before we hit dominatee, we must
822 // dominate it
823 return std::none_of(It, AccessList->rend(),
824 [&](const MemoryAccess &MA) { return &MA == Dominatee; });
825}
826
827const static char LiveOnEntryStr[] = "liveOnEntry";
828
829void MemoryDef::print(raw_ostream &OS) const {
830 MemoryAccess *UO = getDefiningAccess();
831
832 OS << getID() << " = MemoryDef(";
833 if (UO && UO->getID())
834 OS << UO->getID();
835 else
836 OS << LiveOnEntryStr;
837 OS << ')';
838}
839
840void MemoryPhi::print(raw_ostream &OS) const {
841 bool First = true;
842 OS << getID() << " = MemoryPhi(";
843 for (const auto &Op : operands()) {
844 BasicBlock *BB = getIncomingBlock(Op);
845 MemoryAccess *MA = cast<MemoryAccess>(Op);
846 if (!First)
847 OS << ',';
848 else
849 First = false;
850
851 OS << '{';
852 if (BB->hasName())
853 OS << BB->getName();
854 else
855 BB->printAsOperand(OS, false);
856 OS << ',';
857 if (unsigned ID = MA->getID())
858 OS << ID;
859 else
860 OS << LiveOnEntryStr;
861 OS << '}';
862 }
863 OS << ')';
864}
865
866MemoryAccess::~MemoryAccess() {}
867
868void MemoryUse::print(raw_ostream &OS) const {
869 MemoryAccess *UO = getDefiningAccess();
870 OS << "MemoryUse(";
871 if (UO && UO->getID())
872 OS << UO->getID();
873 else
874 OS << LiveOnEntryStr;
875 OS << ')';
876}
877
878void MemoryAccess::dump() const {
879 print(dbgs());
880 dbgs() << "\n";
881}
882
Geoff Berryb96d3b22016-06-01 21:30:40 +0000883char MemorySSAAnalysis::PassID;
George Burgess IVe1100f52016-02-02 22:46:49 +0000884
Geoff Berryb96d3b22016-06-01 21:30:40 +0000885MemorySSA MemorySSAAnalysis::run(Function &F, AnalysisManager<Function> &AM) {
886 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
887 auto &AA = AM.getResult<AAManager>(F);
888 return MemorySSA(F, &AA, &DT);
George Burgess IVe1100f52016-02-02 22:46:49 +0000889}
890
Geoff Berryb96d3b22016-06-01 21:30:40 +0000891PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
892 FunctionAnalysisManager &AM) {
893 OS << "MemorySSA for function: " << F.getName() << "\n";
894 AM.getResult<MemorySSAAnalysis>(F).print(OS);
895
896 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +0000897}
898
Geoff Berryb96d3b22016-06-01 21:30:40 +0000899PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
900 FunctionAnalysisManager &AM) {
901 AM.getResult<MemorySSAAnalysis>(F).verifyMemorySSA();
902
903 return PreservedAnalyses::all();
904}
905
906char MemorySSAWrapperPass::ID = 0;
907
908MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
909 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
910}
911
912void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
913
914void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +0000915 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +0000916 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
917 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +0000918}
919
Geoff Berryb96d3b22016-06-01 21:30:40 +0000920bool MemorySSAWrapperPass::runOnFunction(Function &F) {
921 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
922 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
923 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +0000924 return false;
925}
926
Geoff Berryb96d3b22016-06-01 21:30:40 +0000927void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +0000928
Geoff Berryb96d3b22016-06-01 21:30:40 +0000929void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +0000930 MSSA->print(OS);
931}
932
George Burgess IVe1100f52016-02-02 22:46:49 +0000933MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
934
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000935MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A,
936 DominatorTree *D)
George Burgess IVe1100f52016-02-02 22:46:49 +0000937 : MemorySSAWalker(M), AA(A), DT(D) {}
938
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000939MemorySSA::CachingWalker::~CachingWalker() {}
George Burgess IVe1100f52016-02-02 22:46:49 +0000940
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000941struct MemorySSA::CachingWalker::UpwardsMemoryQuery {
George Burgess IVe1100f52016-02-02 22:46:49 +0000942 // True if we saw a phi whose predecessor was a backedge
943 bool SawBackedgePhi;
944 // True if our original query started off as a call
945 bool IsCall;
946 // The pointer location we started the query with. This will be empty if
947 // IsCall is true.
948 MemoryLocation StartingLoc;
949 // This is the instruction we were querying about.
950 const Instruction *Inst;
951 // Set of visited Instructions for this query.
952 DenseSet<MemoryAccessPair> Visited;
George Burgess IV49cad7d2016-03-30 03:12:08 +0000953 // Vector of visited call accesses for this query. This is separated out
954 // because you can always cache and lookup the result of call queries (IE when
955 // IsCall == true) for every call in the chain. The calls have no AA location
George Burgess IVe1100f52016-02-02 22:46:49 +0000956 // associated with them with them, and thus, no context dependence.
George Burgess IV49cad7d2016-03-30 03:12:08 +0000957 SmallVector<const MemoryAccess *, 32> VisitedCalls;
George Burgess IVe1100f52016-02-02 22:46:49 +0000958 // The MemoryAccess we actually got called with, used to test local domination
959 const MemoryAccess *OriginalAccess;
George Burgess IVe1100f52016-02-02 22:46:49 +0000960
961 UpwardsMemoryQuery()
962 : SawBackedgePhi(false), IsCall(false), Inst(nullptr),
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000963 OriginalAccess(nullptr) {}
964
965 UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
966 : SawBackedgePhi(false), IsCall(ImmutableCallSite(Inst)), Inst(Inst),
967 OriginalAccess(Access) {}
George Burgess IVe1100f52016-02-02 22:46:49 +0000968};
969
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000970void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) {
Daniel Berlin83fc77b2016-03-01 18:46:54 +0000971
972 // TODO: We can do much better cache invalidation with differently stored
973 // caches. For now, for MemoryUses, we simply remove them
974 // from the cache, and kill the entire call/non-call cache for everything
975 // else. The problem is for phis or defs, currently we'd need to follow use
976 // chains down and invalidate anything below us in the chain that currently
977 // terminates at this access.
978
979 // See if this is a MemoryUse, if so, just remove the cached info. MemoryUse
980 // is by definition never a barrier, so nothing in the cache could point to
981 // this use. In that case, we only need invalidate the info for the use
982 // itself.
983
984 if (MemoryUse *MU = dyn_cast<MemoryUse>(MA)) {
985 UpwardsMemoryQuery Q;
986 Instruction *I = MU->getMemoryInst();
987 Q.IsCall = bool(ImmutableCallSite(I));
988 Q.Inst = I;
989 if (!Q.IsCall)
990 Q.StartingLoc = MemoryLocation::get(I);
991 doCacheRemove(MA, Q, Q.StartingLoc);
Geoff Berry9fe26e62016-04-22 14:44:10 +0000992 } else {
993 // If it is not a use, the best we can do right now is destroy the cache.
Daniel Berlin83fc77b2016-03-01 18:46:54 +0000994 CachedUpwardsClobberingCall.clear();
Daniel Berlin83fc77b2016-03-01 18:46:54 +0000995 CachedUpwardsClobberingAccess.clear();
Geoff Berry9fe26e62016-04-22 14:44:10 +0000996 }
997
Filipe Cabecinhas0da99372016-04-29 15:22:48 +0000998#ifdef EXPENSIVE_CHECKS
Geoff Berry9fe26e62016-04-22 14:44:10 +0000999 // Run this only when expensive checks are enabled.
1000 verifyRemoved(MA);
1001#endif
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001002}
1003
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001004void MemorySSA::CachingWalker::doCacheRemove(const MemoryAccess *M,
1005 const UpwardsMemoryQuery &Q,
1006 const MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001007 if (Q.IsCall)
1008 CachedUpwardsClobberingCall.erase(M);
1009 else
1010 CachedUpwardsClobberingAccess.erase({M, Loc});
1011}
1012
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001013void MemorySSA::CachingWalker::doCacheInsert(const MemoryAccess *M,
1014 MemoryAccess *Result,
1015 const UpwardsMemoryQuery &Q,
1016 const MemoryLocation &Loc) {
George Burgess IV1b1fef32016-04-29 18:42:55 +00001017 // This is fine for Phis, since there are times where we can't optimize them.
1018 // Making a def its own clobber is never correct, though.
1019 assert((Result != M || isa<MemoryPhi>(M)) &&
1020 "Something can't clobber itself!");
George Burgess IVe1100f52016-02-02 22:46:49 +00001021 ++NumClobberCacheInserts;
1022 if (Q.IsCall)
1023 CachedUpwardsClobberingCall[M] = Result;
1024 else
1025 CachedUpwardsClobberingAccess[{M, Loc}] = Result;
1026}
1027
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001028MemoryAccess *
1029MemorySSA::CachingWalker::doCacheLookup(const MemoryAccess *M,
1030 const UpwardsMemoryQuery &Q,
1031 const MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001032 ++NumClobberCacheLookups;
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001033 MemoryAccess *Result;
George Burgess IVe1100f52016-02-02 22:46:49 +00001034
1035 if (Q.IsCall)
1036 Result = CachedUpwardsClobberingCall.lookup(M);
1037 else
1038 Result = CachedUpwardsClobberingAccess.lookup({M, Loc});
1039
1040 if (Result)
1041 ++NumClobberCacheHits;
1042 return Result;
1043}
1044
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001045bool MemorySSA::CachingWalker::instructionClobbersQuery(
George Burgess IVe1100f52016-02-02 22:46:49 +00001046 const MemoryDef *MD, UpwardsMemoryQuery &Q,
1047 const MemoryLocation &Loc) const {
1048 Instruction *DefMemoryInst = MD->getMemoryInst();
1049 assert(DefMemoryInst && "Defining instruction not actually an instruction");
1050
1051 if (!Q.IsCall)
1052 return AA->getModRefInfo(DefMemoryInst, Loc) & MRI_Mod;
1053
1054 // If this is a call, mark it for caching
1055 if (ImmutableCallSite(DefMemoryInst))
George Burgess IV49cad7d2016-03-30 03:12:08 +00001056 Q.VisitedCalls.push_back(MD);
George Burgess IVe1100f52016-02-02 22:46:49 +00001057 ModRefInfo I = AA->getModRefInfo(DefMemoryInst, ImmutableCallSite(Q.Inst));
1058 return I != MRI_NoModRef;
1059}
1060
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001061MemoryAccessPair MemorySSA::CachingWalker::UpwardsDFSWalk(
George Burgess IVe1100f52016-02-02 22:46:49 +00001062 MemoryAccess *StartingAccess, const MemoryLocation &Loc,
1063 UpwardsMemoryQuery &Q, bool FollowingBackedge) {
1064 MemoryAccess *ModifyingAccess = nullptr;
1065
1066 auto DFI = df_begin(StartingAccess);
1067 for (auto DFE = df_end(StartingAccess); DFI != DFE;) {
1068 MemoryAccess *CurrAccess = *DFI;
1069 if (MSSA->isLiveOnEntryDef(CurrAccess))
1070 return {CurrAccess, Loc};
George Burgess IV1b1fef32016-04-29 18:42:55 +00001071 // If this is a MemoryDef, check whether it clobbers our current query. This
1072 // needs to be done before consulting the cache, because the cache reports
1073 // the clobber for CurrAccess. If CurrAccess is a clobber for this query,
1074 // and we ask the cache for information first, then we might skip this
1075 // clobber, which is bad.
George Burgess IVe1100f52016-02-02 22:46:49 +00001076 if (auto *MD = dyn_cast<MemoryDef>(CurrAccess)) {
1077 // If we hit the top, stop following this path.
1078 // While we can do lookups, we can't sanely do inserts here unless we were
1079 // to track everything we saw along the way, since we don't know where we
1080 // will stop.
1081 if (instructionClobbersQuery(MD, Q, Loc)) {
1082 ModifyingAccess = CurrAccess;
1083 break;
1084 }
1085 }
George Burgess IV1b1fef32016-04-29 18:42:55 +00001086 if (auto CacheResult = doCacheLookup(CurrAccess, Q, Loc))
1087 return {CacheResult, Loc};
George Burgess IVe1100f52016-02-02 22:46:49 +00001088
1089 // We need to know whether it is a phi so we can track backedges.
1090 // Otherwise, walk all upward defs.
1091 if (!isa<MemoryPhi>(CurrAccess)) {
1092 ++DFI;
1093 continue;
1094 }
1095
George Burgess IV0e489862016-03-23 18:31:55 +00001096#ifndef NDEBUG
1097 // The loop below visits the phi's children for us. Because phis are the
1098 // only things with multiple edges, skipping the children should always lead
1099 // us to the end of the loop.
1100 //
1101 // Use a copy of DFI because skipChildren would kill our search stack, which
1102 // would make caching anything on the way back impossible.
1103 auto DFICopy = DFI;
1104 assert(DFICopy.skipChildren() == DFE &&
1105 "Skipping phi's children doesn't end the DFS?");
1106#endif
1107
George Burgess IV82ee9422016-03-30 00:26:26 +00001108 const MemoryAccessPair PHIPair(CurrAccess, Loc);
1109
1110 // Don't try to optimize this phi again if we've already tried to do so.
1111 if (!Q.Visited.insert(PHIPair).second) {
1112 ModifyingAccess = CurrAccess;
1113 break;
1114 }
1115
George Burgess IV49cad7d2016-03-30 03:12:08 +00001116 std::size_t InitialVisitedCallSize = Q.VisitedCalls.size();
1117
George Burgess IVe1100f52016-02-02 22:46:49 +00001118 // Recurse on PHI nodes, since we need to change locations.
1119 // TODO: Allow graphtraits on pairs, which would turn this whole function
1120 // into a normal single depth first walk.
1121 MemoryAccess *FirstDef = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001122 for (auto MPI = upward_defs_begin(PHIPair), MPE = upward_defs_end();
1123 MPI != MPE; ++MPI) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001124 bool Backedge =
1125 !FollowingBackedge &&
1126 DT->dominates(CurrAccess->getBlock(), MPI.getPhiArgBlock());
1127
1128 MemoryAccessPair CurrentPair =
1129 UpwardsDFSWalk(MPI->first, MPI->second, Q, Backedge);
1130 // All the phi arguments should reach the same point if we can bypass
1131 // this phi. The alternative is that they hit this phi node, which
1132 // means we can skip this argument.
1133 if (FirstDef && CurrentPair.first != PHIPair.first &&
1134 CurrentPair.first != FirstDef) {
1135 ModifyingAccess = CurrAccess;
1136 break;
1137 }
1138
1139 if (!FirstDef)
1140 FirstDef = CurrentPair.first;
George Burgess IVe1100f52016-02-02 22:46:49 +00001141 }
1142
George Burgess IV0e489862016-03-23 18:31:55 +00001143 // If we exited the loop early, go with the result it gave us.
1144 if (!ModifyingAccess) {
George Burgess IV82ee9422016-03-30 00:26:26 +00001145 assert(FirstDef && "Found a Phi with no upward defs?");
1146 ModifyingAccess = FirstDef;
George Burgess IV49cad7d2016-03-30 03:12:08 +00001147 } else {
1148 // If we can't optimize this Phi, then we can't safely cache any of the
1149 // calls we visited when trying to optimize it. Wipe them out now.
1150 Q.VisitedCalls.resize(InitialVisitedCallSize);
George Burgess IV0e489862016-03-23 18:31:55 +00001151 }
1152 break;
George Burgess IVe1100f52016-02-02 22:46:49 +00001153 }
1154
1155 if (!ModifyingAccess)
1156 return {MSSA->getLiveOnEntryDef(), Q.StartingLoc};
1157
George Burgess IV0e489862016-03-23 18:31:55 +00001158 const BasicBlock *OriginalBlock = StartingAccess->getBlock();
George Burgess IV1b1fef32016-04-29 18:42:55 +00001159 assert(DFI.getPathLength() > 0 && "We dropped our path?");
George Burgess IVe1100f52016-02-02 22:46:49 +00001160 unsigned N = DFI.getPathLength();
George Burgess IV1b1fef32016-04-29 18:42:55 +00001161 // If we found a clobbering def, the last element in the path will be our
1162 // clobber, so we don't want to cache that to itself. OTOH, if we optimized a
1163 // phi, we can add the last thing in the path to the cache, since that won't
1164 // be the result.
1165 if (DFI.getPath(N - 1) == ModifyingAccess)
1166 --N;
1167 for (; N > 1; --N) {
George Burgess IV0e489862016-03-23 18:31:55 +00001168 MemoryAccess *CacheAccess = DFI.getPath(N - 1);
1169 BasicBlock *CurrBlock = CacheAccess->getBlock();
George Burgess IVe1100f52016-02-02 22:46:49 +00001170 if (!FollowingBackedge)
George Burgess IV0e489862016-03-23 18:31:55 +00001171 doCacheInsert(CacheAccess, ModifyingAccess, Q, Loc);
George Burgess IVe1100f52016-02-02 22:46:49 +00001172 if (DT->dominates(CurrBlock, OriginalBlock) &&
1173 (CurrBlock != OriginalBlock || !FollowingBackedge ||
George Burgess IV0e489862016-03-23 18:31:55 +00001174 MSSA->locallyDominates(CacheAccess, StartingAccess)))
George Burgess IVe1100f52016-02-02 22:46:49 +00001175 break;
1176 }
1177
1178 // Cache everything else on the way back. The caller should cache
George Burgess IV1b1fef32016-04-29 18:42:55 +00001179 // StartingAccess for us.
1180 for (; N > 1; --N) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001181 MemoryAccess *CacheAccess = DFI.getPath(N - 1);
1182 doCacheInsert(CacheAccess, ModifyingAccess, Q, Loc);
1183 }
1184 assert(Q.Visited.size() < 1000 && "Visited too much");
1185
1186 return {ModifyingAccess, Loc};
1187}
1188
1189/// \brief Walk the use-def chains starting at \p MA and find
1190/// the MemoryAccess that actually clobbers Loc.
1191///
1192/// \returns our clobbering memory access
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001193MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
1194 MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001195 return UpwardsDFSWalk(StartingAccess, Q.StartingLoc, Q, false).first;
1196}
1197
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001198MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
1199 MemoryAccess *StartingAccess, MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001200 if (isa<MemoryPhi>(StartingAccess))
1201 return StartingAccess;
1202
1203 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
1204 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
1205 return StartingUseOrDef;
1206
1207 Instruction *I = StartingUseOrDef->getMemoryInst();
1208
1209 // Conservatively, fences are always clobbers, so don't perform the walk if we
1210 // hit a fence.
1211 if (isa<FenceInst>(I))
1212 return StartingUseOrDef;
1213
1214 UpwardsMemoryQuery Q;
1215 Q.OriginalAccess = StartingUseOrDef;
1216 Q.StartingLoc = Loc;
1217 Q.Inst = StartingUseOrDef->getMemoryInst();
1218 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00001219
1220 if (auto CacheResult = doCacheLookup(StartingUseOrDef, Q, Q.StartingLoc))
1221 return CacheResult;
1222
1223 // Unlike the other function, do not walk to the def of a def, because we are
1224 // handed something we already believe is the clobbering access.
1225 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
1226 ? StartingUseOrDef->getDefiningAccess()
1227 : StartingUseOrDef;
1228
1229 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IV1b1fef32016-04-29 18:42:55 +00001230 // Only cache this if it wouldn't make Clobber point to itself.
1231 if (Clobber != StartingAccess)
1232 doCacheInsert(Q.OriginalAccess, Clobber, Q, Q.StartingLoc);
George Burgess IVe1100f52016-02-02 22:46:49 +00001233 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
1234 DEBUG(dbgs() << *StartingUseOrDef << "\n");
1235 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
1236 DEBUG(dbgs() << *Clobber << "\n");
1237 return Clobber;
1238}
1239
1240MemoryAccess *
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001241MemorySSA::CachingWalker::getClobberingMemoryAccess(const Instruction *I) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001242 // There should be no way to lookup an instruction and get a phi as the
1243 // access, since we only map BB's to PHI's. So, this must be a use or def.
1244 auto *StartingAccess = cast<MemoryUseOrDef>(MSSA->getMemoryAccess(I));
1245
1246 // We can't sanely do anything with a FenceInst, they conservatively
1247 // clobber all memory, and have no locations to get pointers from to
1248 // try to disambiguate
1249 if (isa<FenceInst>(I))
1250 return StartingAccess;
1251
1252 UpwardsMemoryQuery Q;
1253 Q.OriginalAccess = StartingAccess;
1254 Q.IsCall = bool(ImmutableCallSite(I));
1255 if (!Q.IsCall)
1256 Q.StartingLoc = MemoryLocation::get(I);
1257 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00001258 if (auto CacheResult = doCacheLookup(StartingAccess, Q, Q.StartingLoc))
1259 return CacheResult;
1260
1261 // Start with the thing we already think clobbers this location
1262 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
1263
1264 // At this point, DefiningAccess may be the live on entry def.
1265 // If it is, we will not get a better result.
1266 if (MSSA->isLiveOnEntryDef(DefiningAccess))
1267 return DefiningAccess;
1268
1269 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IV1b1fef32016-04-29 18:42:55 +00001270 // DFS won't cache a result for DefiningAccess. So, if DefiningAccess isn't
1271 // our clobber, be sure that it gets a cache entry, too.
1272 if (Result != DefiningAccess)
1273 doCacheInsert(DefiningAccess, Result, Q, Q.StartingLoc);
George Burgess IVe1100f52016-02-02 22:46:49 +00001274 doCacheInsert(Q.OriginalAccess, Result, Q, Q.StartingLoc);
1275 // TODO: When this implementation is more mature, we may want to figure out
1276 // what this additional caching buys us. It's most likely A Good Thing.
1277 if (Q.IsCall)
1278 for (const MemoryAccess *MA : Q.VisitedCalls)
George Burgess IV1b1fef32016-04-29 18:42:55 +00001279 if (MA != Result)
1280 doCacheInsert(MA, Result, Q, Q.StartingLoc);
George Burgess IVe1100f52016-02-02 22:46:49 +00001281
1282 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
1283 DEBUG(dbgs() << *DefiningAccess << "\n");
1284 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
1285 DEBUG(dbgs() << *Result << "\n");
1286
1287 return Result;
1288}
1289
Geoff Berry9fe26e62016-04-22 14:44:10 +00001290// Verify that MA doesn't exist in any of the caches.
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001291void MemorySSA::CachingWalker::verifyRemoved(MemoryAccess *MA) {
Geoff Berry9fe26e62016-04-22 14:44:10 +00001292#ifndef NDEBUG
1293 for (auto &P : CachedUpwardsClobberingAccess)
1294 assert(P.first.first != MA && P.second != MA &&
1295 "Found removed MemoryAccess in cache.");
1296 for (auto &P : CachedUpwardsClobberingCall)
1297 assert(P.first != MA && P.second != MA &&
1298 "Found removed MemoryAccess in cache.");
1299#endif // !NDEBUG
1300}
1301
George Burgess IVe1100f52016-02-02 22:46:49 +00001302MemoryAccess *
1303DoNothingMemorySSAWalker::getClobberingMemoryAccess(const Instruction *I) {
1304 MemoryAccess *MA = MSSA->getMemoryAccess(I);
1305 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
1306 return Use->getDefiningAccess();
1307 return MA;
1308}
1309
1310MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
1311 MemoryAccess *StartingAccess, MemoryLocation &) {
1312 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
1313 return Use->getDefiningAccess();
1314 return StartingAccess;
1315}
1316}