blob: a52ea34e77b5b63611b1edee03127f54bd2a105e [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//===----------------------------------------------------------------===//
Mehdi Aminib550cb12016-04-18 09:17:29 +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 {
58
59/// \brief An assembly annotator class to print Memory SSA information in
60/// comments.
61class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
62 friend class MemorySSA;
63 const MemorySSA *MSSA;
64
65public:
66 MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
67
68 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
69 formatted_raw_ostream &OS) {
70 if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
71 OS << "; " << *MA << "\n";
72 }
73
74 virtual void emitInstructionAnnot(const Instruction *I,
75 formatted_raw_ostream &OS) {
76 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
77 OS << "; " << *MA << "\n";
78 }
79};
80}
81
82namespace {
83struct RenamePassData {
84 DomTreeNode *DTN;
85 DomTreeNode::const_iterator ChildIt;
86 MemoryAccess *IncomingVal;
87
88 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
89 MemoryAccess *M)
90 : DTN(D), ChildIt(It), IncomingVal(M) {}
91 void swap(RenamePassData &RHS) {
92 std::swap(DTN, RHS.DTN);
93 std::swap(ChildIt, RHS.ChildIt);
94 std::swap(IncomingVal, RHS.IncomingVal);
95 }
96};
97}
98
99namespace llvm {
100/// \brief Rename a single basic block into MemorySSA form.
101/// Uses the standard SSA renaming algorithm.
102/// \returns The new incoming value.
103MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB,
104 MemoryAccess *IncomingVal) {
105 auto It = PerBlockAccesses.find(BB);
106 // Skip most processing if the list is empty.
107 if (It != PerBlockAccesses.end()) {
Daniel Berlinada263d2016-06-20 20:21:33 +0000108 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000109 for (MemoryAccess &L : *Accesses) {
110 switch (L.getValueID()) {
111 case Value::MemoryUseVal:
112 cast<MemoryUse>(&L)->setDefiningAccess(IncomingVal);
113 break;
114 case Value::MemoryDefVal:
115 // We can't legally optimize defs, because we only allow single
116 // memory phis/uses on operations, and if we optimize these, we can
117 // end up with multiple reaching defs. Uses do not have this
118 // problem, since they do not produce a value
119 cast<MemoryDef>(&L)->setDefiningAccess(IncomingVal);
120 IncomingVal = &L;
121 break;
122 case Value::MemoryPhiVal:
123 IncomingVal = &L;
124 break;
125 }
126 }
127 }
128
129 // Pass through values to our successors
130 for (const BasicBlock *S : successors(BB)) {
131 auto It = PerBlockAccesses.find(S);
132 // Rename the phi nodes in our successor block
133 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
134 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +0000135 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000136 auto *Phi = cast<MemoryPhi>(&Accesses->front());
137 assert(std::find(succ_begin(BB), succ_end(BB), S) != succ_end(BB) &&
138 "Must be at least one edge from Succ to BB!");
139 Phi->addIncoming(IncomingVal, BB);
140 }
141
142 return IncomingVal;
143}
144
145/// \brief This is the standard SSA renaming algorithm.
146///
147/// We walk the dominator tree in preorder, renaming accesses, and then filling
148/// in phi nodes in our successors.
149void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
150 SmallPtrSet<BasicBlock *, 16> &Visited) {
151 SmallVector<RenamePassData, 32> WorkStack;
152 IncomingVal = renameBlock(Root->getBlock(), IncomingVal);
153 WorkStack.push_back({Root, Root->begin(), IncomingVal});
154 Visited.insert(Root->getBlock());
155
156 while (!WorkStack.empty()) {
157 DomTreeNode *Node = WorkStack.back().DTN;
158 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
159 IncomingVal = WorkStack.back().IncomingVal;
160
161 if (ChildIt == Node->end()) {
162 WorkStack.pop_back();
163 } else {
164 DomTreeNode *Child = *ChildIt;
165 ++WorkStack.back().ChildIt;
166 BasicBlock *BB = Child->getBlock();
167 Visited.insert(BB);
168 IncomingVal = renameBlock(BB, IncomingVal);
169 WorkStack.push_back({Child, Child->begin(), IncomingVal});
170 }
171 }
172}
173
174/// \brief Compute dominator levels, used by the phi insertion algorithm above.
175void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) {
176 for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode());
177 DFI != DFE; ++DFI)
178 DomLevels[*DFI] = DFI.getPathLength() - 1;
179}
180
181/// \brief This handles unreachable block acccesses by deleting phi nodes in
182/// unreachable blocks, and marking all other unreachable MemoryAccess's as
183/// being uses of the live on entry definition.
184void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
185 assert(!DT->isReachableFromEntry(BB) &&
186 "Reachable block found while handling unreachable blocks");
187
188 auto It = PerBlockAccesses.find(BB);
189 if (It == PerBlockAccesses.end())
190 return;
191
192 auto &Accesses = It->second;
193 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
194 auto Next = std::next(AI);
195 // If we have a phi, just remove it. We are going to replace all
196 // users with live on entry.
197 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
198 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
199 else
200 Accesses->erase(AI);
201 AI = Next;
202 }
203}
204
Geoff Berryb96d3b22016-06-01 21:30:40 +0000205MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
206 : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
207 NextID(0) {
208 getWalker(); // Ensure MemorySSA has been built.
209}
210
211MemorySSA::MemorySSA(MemorySSA &&MSSA)
212 : AA(MSSA.AA), DT(MSSA.DT), F(MSSA.F),
213 ValueToMemoryAccess(std::move(MSSA.ValueToMemoryAccess)),
214 PerBlockAccesses(std::move(MSSA.PerBlockAccesses)),
215 LiveOnEntryDef(std::move(MSSA.LiveOnEntryDef)),
216 Walker(std::move(MSSA.Walker)), NextID(MSSA.NextID) {
217 // Update the Walker MSSA pointer so it doesn't point to the moved-from MSSA
218 // object any more.
219 Walker->MSSA = this;
220}
George Burgess IVe1100f52016-02-02 22:46:49 +0000221
222MemorySSA::~MemorySSA() {
223 // Drop all our references
224 for (const auto &Pair : PerBlockAccesses)
225 for (MemoryAccess &MA : *Pair.second)
226 MA.dropAllReferences();
227}
228
Daniel Berlin14300262016-06-21 18:39:20 +0000229MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +0000230 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
231
232 if (Res.second)
Daniel Berlinada263d2016-06-20 20:21:33 +0000233 Res.first->second = make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +0000234 return Res.first->second.get();
235}
236
Geoff Berryb96d3b22016-06-01 21:30:40 +0000237MemorySSAWalker *MemorySSA::getWalker() {
George Burgess IVe1100f52016-02-02 22:46:49 +0000238 if (Walker)
Geoff Berryb96d3b22016-06-01 21:30:40 +0000239 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000240
Geoff Berryb96d3b22016-06-01 21:30:40 +0000241 Walker = make_unique<CachingMemorySSAWalker>(this, AA, DT);
George Burgess IVe1100f52016-02-02 22:46:49 +0000242
243 // We create an access to represent "live on entry", for things like
244 // arguments or users of globals, where the memory they use is defined before
245 // the beginning of the function. We do not actually insert it into the IR.
246 // We do not define a live on exit for the immediate uses, and thus our
247 // semantics do *not* imply that something with no immediate uses can simply
248 // be removed.
249 BasicBlock &StartingPoint = F.getEntryBlock();
250 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
251 &StartingPoint, NextID++);
252
253 // We maintain lists of memory accesses per-block, trading memory for time. We
254 // could just look up the memory access for every possible instruction in the
255 // stream.
256 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
Daniel Berlin1b51a292016-02-07 01:52:19 +0000257 SmallPtrSet<BasicBlock *, 32> DefUseBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +0000258 // Go through each block, figure out where defs occur, and chain together all
259 // the accesses.
260 for (BasicBlock &B : F) {
Daniel Berlin7898ca62016-02-07 01:52:15 +0000261 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +0000262 AccessList *Accesses = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +0000263 for (Instruction &I : B) {
Peter Collingbourneffecb142016-05-26 01:19:17 +0000264 MemoryUseOrDef *MUD = createNewAccess(&I);
George Burgess IVb42b7622016-03-11 19:34:03 +0000265 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +0000266 continue;
George Burgess IV3887a412016-03-21 21:25:39 +0000267 InsertIntoDef |= isa<MemoryDef>(MUD);
Daniel Berlin1b51a292016-02-07 01:52:19 +0000268
George Burgess IVe1100f52016-02-02 22:46:49 +0000269 if (!Accesses)
270 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +0000271 Accesses->push_back(MUD);
George Burgess IVe1100f52016-02-02 22:46:49 +0000272 }
Daniel Berlin7898ca62016-02-07 01:52:15 +0000273 if (InsertIntoDef)
274 DefiningBlocks.insert(&B);
George Burgess IV3887a412016-03-21 21:25:39 +0000275 if (Accesses)
Daniel Berlin1b51a292016-02-07 01:52:19 +0000276 DefUseBlocks.insert(&B);
277 }
278
279 // Compute live-in.
280 // Live in is normally defined as "all the blocks on the path from each def to
281 // each of it's uses".
282 // MemoryDef's are implicit uses of previous state, so they are also uses.
283 // This means we don't really have def-only instructions. The only
284 // MemoryDef's that are not really uses are those that are of the LiveOnEntry
285 // variable (because LiveOnEntry can reach anywhere, and every def is a
286 // must-kill of LiveOnEntry).
287 // In theory, you could precisely compute live-in by using alias-analysis to
288 // disambiguate defs and uses to see which really pair up with which.
289 // In practice, this would be really expensive and difficult. So we simply
290 // assume all defs are also uses that need to be kept live.
291 // Because of this, the end result of this live-in computation will be "the
292 // entire set of basic blocks that reach any use".
293
294 SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
295 SmallVector<BasicBlock *, 64> LiveInBlockWorklist(DefUseBlocks.begin(),
296 DefUseBlocks.end());
297 // Now that we have a set of blocks where a value is live-in, recursively add
298 // predecessors until we find the full region the value is live.
299 while (!LiveInBlockWorklist.empty()) {
300 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
301
302 // The block really is live in here, insert it into the set. If already in
303 // the set, then it has already been processed.
304 if (!LiveInBlocks.insert(BB).second)
305 continue;
306
307 // Since the value is live into BB, it is either defined in a predecessor or
308 // live into it to.
309 LiveInBlockWorklist.append(pred_begin(BB), pred_end(BB));
George Burgess IVe1100f52016-02-02 22:46:49 +0000310 }
311
312 // Determine where our MemoryPhi's should go
Daniel Berlin77fa84e2016-04-19 06:13:28 +0000313 ForwardIDFCalculator IDFs(*DT);
George Burgess IVe1100f52016-02-02 22:46:49 +0000314 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin1b51a292016-02-07 01:52:19 +0000315 IDFs.setLiveInBlocks(LiveInBlocks);
George Burgess IVe1100f52016-02-02 22:46:49 +0000316 SmallVector<BasicBlock *, 32> IDFBlocks;
317 IDFs.calculate(IDFBlocks);
318
319 // Now place MemoryPhi nodes.
320 for (auto &BB : IDFBlocks) {
321 // Insert phi node
Daniel Berlinada263d2016-06-20 20:21:33 +0000322 AccessList *Accesses = getOrCreateAccessList(BB);
Daniel Berlin14300262016-06-21 18:39:20 +0000323 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlinf6c9ae92016-02-10 17:41:25 +0000324 ValueToMemoryAccess.insert(std::make_pair(BB, Phi));
George Burgess IVe1100f52016-02-02 22:46:49 +0000325 // Phi's always are placed at the front of the block.
326 Accesses->push_front(Phi);
327 }
328
329 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
330 // filled in with all blocks.
331 SmallPtrSet<BasicBlock *, 16> Visited;
332 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
333
334 // Now optimize the MemoryUse's defining access to point to the nearest
335 // dominating clobbering def.
336 // This ensures that MemoryUse's that are killed by the same store are
337 // immediate users of that store, one of the invariants we guarantee.
338 for (auto DomNode : depth_first(DT)) {
339 BasicBlock *BB = DomNode->getBlock();
340 auto AI = PerBlockAccesses.find(BB);
341 if (AI == PerBlockAccesses.end())
342 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +0000343 AccessList *Accesses = AI->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000344 for (auto &MA : *Accesses) {
345 if (auto *MU = dyn_cast<MemoryUse>(&MA)) {
346 Instruction *Inst = MU->getMemoryInst();
Daniel Berlin64120022016-03-02 21:16:28 +0000347 MU->setDefiningAccess(Walker->getClobberingMemoryAccess(Inst));
George Burgess IVe1100f52016-02-02 22:46:49 +0000348 }
349 }
350 }
351
352 // Mark the uses in unreachable blocks as live on entry, so that they go
353 // somewhere.
354 for (auto &BB : F)
355 if (!Visited.count(&BB))
356 markUnreachableAsLiveOnEntry(&BB);
357
Geoff Berryb96d3b22016-06-01 21:30:40 +0000358 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000359}
360
Daniel Berlin14300262016-06-21 18:39:20 +0000361MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
362 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
363 AccessList *Accesses = getOrCreateAccessList(BB);
364 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
365 ValueToMemoryAccess.insert(std::make_pair(BB, Phi));
366 // Phi's always are placed at the front of the block.
367 Accesses->push_front(Phi);
368 return Phi;
369}
370
371MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
372 MemoryAccess *Definition) {
373 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
374 MemoryUseOrDef *NewAccess = createNewAccess(I);
375 assert(
376 NewAccess != nullptr &&
377 "Tried to create a memory access for a non-memory touching instruction");
378 NewAccess->setDefiningAccess(Definition);
379 return NewAccess;
380}
381
382MemoryAccess *MemorySSA::createMemoryAccessInBB(Instruction *I,
383 MemoryAccess *Definition,
384 const BasicBlock *BB,
385 InsertionPlace Point) {
386 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
387 auto *Accesses = getOrCreateAccessList(BB);
388 if (Point == Beginning) {
389 // It goes after any phi nodes
390 auto AI = std::find_if(
391 Accesses->begin(), Accesses->end(),
392 [](const MemoryAccess &MA) { return !isa<MemoryPhi>(MA); });
393
394 Accesses->insert(AI, NewAccess);
395 } else {
396 Accesses->push_back(NewAccess);
397 }
398
399 return NewAccess;
400}
401MemoryAccess *MemorySSA::createMemoryAccessBefore(Instruction *I,
402 MemoryAccess *Definition,
403 MemoryAccess *InsertPt) {
404 assert(I->getParent() == InsertPt->getBlock() &&
405 "New and old access must be in the same block");
406 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
407 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
408 Accesses->insert(AccessList::iterator(InsertPt), NewAccess);
409 return NewAccess;
410}
411
412MemoryAccess *MemorySSA::createMemoryAccessAfter(Instruction *I,
413 MemoryAccess *Definition,
414 MemoryAccess *InsertPt) {
415 assert(I->getParent() == InsertPt->getBlock() &&
416 "New and old access must be in the same block");
417 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
418 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
419 Accesses->insertAfter(AccessList::iterator(InsertPt), NewAccess);
420 return NewAccess;
421}
422
George Burgess IVe1100f52016-02-02 22:46:49 +0000423/// \brief Helper function to create new memory accesses
Peter Collingbourneffecb142016-05-26 01:19:17 +0000424MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +0000425 // The assume intrinsic has a control dependency which we model by claiming
426 // that it writes arbitrarily. Ignore that fake memory dependency here.
427 // FIXME: Replace this special casing with a more accurate modelling of
428 // assume's control dependency.
429 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
430 if (II->getIntrinsicID() == Intrinsic::assume)
431 return nullptr;
432
George Burgess IVe1100f52016-02-02 22:46:49 +0000433 // Find out what affect this instruction has on memory.
434 ModRefInfo ModRef = AA->getModRefInfo(I);
435 bool Def = bool(ModRef & MRI_Mod);
436 bool Use = bool(ModRef & MRI_Ref);
437
438 // It's possible for an instruction to not modify memory at all. During
439 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +0000440 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +0000441 return nullptr;
442
443 assert((Def || Use) &&
444 "Trying to create a memory access with a non-memory instruction");
445
George Burgess IVb42b7622016-03-11 19:34:03 +0000446 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +0000447 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +0000448 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +0000449 else
George Burgess IVb42b7622016-03-11 19:34:03 +0000450 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
451 ValueToMemoryAccess.insert(std::make_pair(I, MUD));
452 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +0000453}
454
455MemoryAccess *MemorySSA::findDominatingDef(BasicBlock *UseBlock,
456 enum InsertionPlace Where) {
457 // Handle the initial case
458 if (Where == Beginning)
459 // The only thing that could define us at the beginning is a phi node
460 if (MemoryPhi *Phi = getMemoryAccess(UseBlock))
461 return Phi;
462
463 DomTreeNode *CurrNode = DT->getNode(UseBlock);
464 // Need to be defined by our dominator
465 if (Where == Beginning)
466 CurrNode = CurrNode->getIDom();
467 Where = End;
468 while (CurrNode) {
469 auto It = PerBlockAccesses.find(CurrNode->getBlock());
470 if (It != PerBlockAccesses.end()) {
471 auto &Accesses = It->second;
472 for (auto RAI = Accesses->rbegin(), RAE = Accesses->rend(); RAI != RAE;
473 ++RAI) {
474 if (isa<MemoryDef>(*RAI) || isa<MemoryPhi>(*RAI))
475 return &*RAI;
476 }
477 }
478 CurrNode = CurrNode->getIDom();
479 }
480 return LiveOnEntryDef.get();
481}
482
483/// \brief Returns true if \p Replacer dominates \p Replacee .
484bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
485 const MemoryAccess *Replacee) const {
486 if (isa<MemoryUseOrDef>(Replacee))
487 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
488 const auto *MP = cast<MemoryPhi>(Replacee);
489 // For a phi node, the use occurs in the predecessor block of the phi node.
490 // Since we may occur multiple times in the phi node, we have to check each
491 // operand to ensure Replacer dominates each operand where Replacee occurs.
492 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +0000493 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +0000494 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
495 return false;
496 }
497 return true;
498}
499
Daniel Berlin83fc77b2016-03-01 18:46:54 +0000500/// \brief If all arguments of a MemoryPHI are defined by the same incoming
501/// argument, return that argument.
502static MemoryAccess *onlySingleValue(MemoryPhi *MP) {
503 MemoryAccess *MA = nullptr;
504
505 for (auto &Arg : MP->operands()) {
506 if (!MA)
507 MA = cast<MemoryAccess>(Arg);
508 else if (MA != Arg)
509 return nullptr;
510 }
511 return MA;
512}
513
514/// \brief Properly remove \p MA from all of MemorySSA's lookup tables.
515///
516/// Because of the way the intrusive list and use lists work, it is important to
517/// do removal in the right order.
518void MemorySSA::removeFromLookups(MemoryAccess *MA) {
519 assert(MA->use_empty() &&
520 "Trying to remove memory access that still has uses");
521 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
522 MUD->setDefiningAccess(nullptr);
523 // Invalidate our walker's cache if necessary
524 if (!isa<MemoryUse>(MA))
525 Walker->invalidateInfo(MA);
526 // The call below to erase will destroy MA, so we can't change the order we
527 // are doing things here
528 Value *MemoryInst;
529 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
530 MemoryInst = MUD->getMemoryInst();
531 } else {
532 MemoryInst = MA->getBlock();
533 }
534 ValueToMemoryAccess.erase(MemoryInst);
535
George Burgess IVe0e6e482016-03-02 02:35:04 +0000536 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
Daniel Berlinada263d2016-06-20 20:21:33 +0000537 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin83fc77b2016-03-01 18:46:54 +0000538 Accesses->erase(MA);
George Burgess IVe0e6e482016-03-02 02:35:04 +0000539 if (Accesses->empty())
540 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +0000541}
542
543void MemorySSA::removeMemoryAccess(MemoryAccess *MA) {
544 assert(!isLiveOnEntryDef(MA) && "Trying to remove the live on entry def");
545 // We can only delete phi nodes if they have no uses, or we can replace all
546 // uses with a single definition.
547 MemoryAccess *NewDefTarget = nullptr;
548 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) {
549 // Note that it is sufficient to know that all edges of the phi node have
550 // the same argument. If they do, by the definition of dominance frontiers
551 // (which we used to place this phi), that argument must dominate this phi,
552 // and thus, must dominate the phi's uses, and so we will not hit the assert
553 // below.
554 NewDefTarget = onlySingleValue(MP);
555 assert((NewDefTarget || MP->use_empty()) &&
556 "We can't delete this memory phi");
557 } else {
558 NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
559 }
560
561 // Re-point the uses at our defining access
562 if (!MA->use_empty())
563 MA->replaceAllUsesWith(NewDefTarget);
564
565 // The call below to erase will destroy MA, so we can't change the order we
566 // are doing things here
567 removeFromLookups(MA);
568}
569
George Burgess IVe1100f52016-02-02 22:46:49 +0000570void MemorySSA::print(raw_ostream &OS) const {
571 MemorySSAAnnotatedWriter Writer(this);
572 F.print(OS, &Writer);
573}
574
575void MemorySSA::dump() const {
576 MemorySSAAnnotatedWriter Writer(this);
577 F.print(dbgs(), &Writer);
578}
579
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000580void MemorySSA::verifyMemorySSA() const {
581 verifyDefUses(F);
582 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +0000583 verifyOrdering(F);
584}
585
586/// \brief Verify that the order and existence of MemoryAccesses matches the
587/// order and existence of memory affecting instructions.
588void MemorySSA::verifyOrdering(Function &F) const {
589 // Walk all the blocks, comparing what the lookups think and what the access
590 // lists think, as well as the order in the blocks vs the order in the access
591 // lists.
592 SmallVector<MemoryAccess *, 32> ActualAccesses;
593 for (BasicBlock &B : F) {
594 const AccessList *AL = getBlockAccesses(&B);
595 MemoryAccess *Phi = getMemoryAccess(&B);
596 if (Phi)
597 ActualAccesses.push_back(Phi);
598 for (Instruction &I : B) {
599 MemoryAccess *MA = getMemoryAccess(&I);
600 assert((!MA || AL) && "We have memory affecting instructions "
601 "in this block but they are not in the "
602 "access list");
603 if (MA)
604 ActualAccesses.push_back(MA);
605 }
606 // Either we hit the assert, really have no accesses, or we have both
607 // accesses and an access list
608 if (!AL)
609 continue;
610 assert(AL->size() == ActualAccesses.size() &&
611 "We don't have the same number of accesses in the block as on the "
612 "access list");
613 auto ALI = AL->begin();
614 auto AAI = ActualAccesses.begin();
615 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
616 assert(&*ALI == *AAI && "Not the same accesses in the same order");
617 ++ALI;
618 ++AAI;
619 }
620 ActualAccesses.clear();
621 }
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000622}
623
George Burgess IVe1100f52016-02-02 22:46:49 +0000624/// \brief Verify the domination properties of MemorySSA by checking that each
625/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000626void MemorySSA::verifyDomination(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +0000627 for (BasicBlock &B : F) {
628 // Phi nodes are attached to basic blocks
629 if (MemoryPhi *MP = getMemoryAccess(&B)) {
630 for (User *U : MP->users()) {
631 BasicBlock *UseBlock;
632 // Phi operands are used on edges, we simulate the right domination by
633 // acting as if the use occurred at the end of the predecessor block.
634 if (MemoryPhi *P = dyn_cast<MemoryPhi>(U)) {
635 for (const auto &Arg : P->operands()) {
636 if (Arg == MP) {
637 UseBlock = P->getIncomingBlock(Arg);
638 break;
639 }
640 }
641 } else {
642 UseBlock = cast<MemoryAccess>(U)->getBlock();
643 }
George Burgess IV60adac42016-02-02 23:26:01 +0000644 (void)UseBlock;
George Burgess IVe1100f52016-02-02 22:46:49 +0000645 assert(DT->dominates(MP->getBlock(), UseBlock) &&
646 "Memory PHI does not dominate it's uses");
647 }
648 }
649
650 for (Instruction &I : B) {
651 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
652 if (!MD)
653 continue;
654
Benjamin Kramer451f54c2016-02-22 13:11:58 +0000655 for (User *U : MD->users()) {
Daniel Berlinada263d2016-06-20 20:21:33 +0000656 BasicBlock *UseBlock;
657 (void)UseBlock;
George Burgess IVe1100f52016-02-02 22:46:49 +0000658 // Things are allowed to flow to phi nodes over their predecessor edge.
659 if (auto *P = dyn_cast<MemoryPhi>(U)) {
660 for (const auto &Arg : P->operands()) {
661 if (Arg == MD) {
662 UseBlock = P->getIncomingBlock(Arg);
663 break;
664 }
665 }
666 } else {
667 UseBlock = cast<MemoryAccess>(U)->getBlock();
668 }
669 assert(DT->dominates(MD->getBlock(), UseBlock) &&
670 "Memory Def does not dominate it's uses");
671 }
672 }
673 }
674}
675
676/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
677/// appears in the use list of \p Def.
678///
679/// llvm_unreachable is used instead of asserts because this may be called in
680/// a build without asserts. In that case, we don't want this to turn into a
681/// nop.
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000682void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
George Burgess IVe1100f52016-02-02 22:46:49 +0000683 // The live on entry use may cause us to get a NULL def here
684 if (!Def) {
685 if (!isLiveOnEntryDef(Use))
686 llvm_unreachable("Null def but use not point to live on entry def");
687 } else if (std::find(Def->user_begin(), Def->user_end(), Use) ==
688 Def->user_end()) {
689 llvm_unreachable("Did not find use in def's use list");
690 }
691}
692
693/// \brief Verify the immediate use information, by walking all the memory
694/// accesses and verifying that, for each use, it appears in the
695/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +0000696void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +0000697 for (BasicBlock &B : F) {
698 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +0000699 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
700 assert(Phi->getNumOperands() ==
701 std::distance(pred_begin(&B), pred_end(&B)) &&
702 "Incomplete MemoryPhi Node");
George Burgess IVe1100f52016-02-02 22:46:49 +0000703 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
704 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Daniel Berlin14300262016-06-21 18:39:20 +0000705 }
George Burgess IVe1100f52016-02-02 22:46:49 +0000706
707 for (Instruction &I : B) {
708 if (MemoryAccess *MA = getMemoryAccess(&I)) {
709 assert(isa<MemoryUseOrDef>(MA) &&
710 "Found a phi node not attached to a bb");
711 verifyUseInDefs(cast<MemoryUseOrDef>(MA)->getDefiningAccess(), MA);
712 }
713 }
714 }
715}
716
717MemoryAccess *MemorySSA::getMemoryAccess(const Value *I) const {
Daniel Berlinf6c9ae92016-02-10 17:41:25 +0000718 return ValueToMemoryAccess.lookup(I);
George Burgess IVe1100f52016-02-02 22:46:49 +0000719}
720
721MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
722 return cast_or_null<MemoryPhi>(getMemoryAccess((const Value *)BB));
723}
724
725/// \brief Determine, for two memory accesses in the same block,
726/// whether \p Dominator dominates \p Dominatee.
727/// \returns True if \p Dominator dominates \p Dominatee.
728bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
729 const MemoryAccess *Dominatee) const {
730
731 assert((Dominator->getBlock() == Dominatee->getBlock()) &&
732 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +0000733
734 // A node dominates itself.
735 if (Dominatee == Dominator)
736 return true;
737
738 // When Dominatee is defined on function entry, it is not dominated by another
739 // memory access.
740 if (isLiveOnEntryDef(Dominatee))
741 return false;
742
743 // When Dominator is defined on function entry, it dominates the other memory
744 // access.
745 if (isLiveOnEntryDef(Dominator))
746 return true;
747
George Burgess IVe1100f52016-02-02 22:46:49 +0000748 // Get the access list for the block
Daniel Berlinada263d2016-06-20 20:21:33 +0000749 const AccessList *AccessList = getBlockAccesses(Dominator->getBlock());
750 AccessList::const_reverse_iterator It(Dominator->getIterator());
George Burgess IVe1100f52016-02-02 22:46:49 +0000751
752 // If we hit the beginning of the access list before we hit dominatee, we must
753 // dominate it
754 return std::none_of(It, AccessList->rend(),
755 [&](const MemoryAccess &MA) { return &MA == Dominatee; });
756}
757
758const static char LiveOnEntryStr[] = "liveOnEntry";
759
760void MemoryDef::print(raw_ostream &OS) const {
761 MemoryAccess *UO = getDefiningAccess();
762
763 OS << getID() << " = MemoryDef(";
764 if (UO && UO->getID())
765 OS << UO->getID();
766 else
767 OS << LiveOnEntryStr;
768 OS << ')';
769}
770
771void MemoryPhi::print(raw_ostream &OS) const {
772 bool First = true;
773 OS << getID() << " = MemoryPhi(";
774 for (const auto &Op : operands()) {
775 BasicBlock *BB = getIncomingBlock(Op);
776 MemoryAccess *MA = cast<MemoryAccess>(Op);
777 if (!First)
778 OS << ',';
779 else
780 First = false;
781
782 OS << '{';
783 if (BB->hasName())
784 OS << BB->getName();
785 else
786 BB->printAsOperand(OS, false);
787 OS << ',';
788 if (unsigned ID = MA->getID())
789 OS << ID;
790 else
791 OS << LiveOnEntryStr;
792 OS << '}';
793 }
794 OS << ')';
795}
796
797MemoryAccess::~MemoryAccess() {}
798
799void MemoryUse::print(raw_ostream &OS) const {
800 MemoryAccess *UO = getDefiningAccess();
801 OS << "MemoryUse(";
802 if (UO && UO->getID())
803 OS << UO->getID();
804 else
805 OS << LiveOnEntryStr;
806 OS << ')';
807}
808
809void MemoryAccess::dump() const {
810 print(dbgs());
811 dbgs() << "\n";
812}
813
Geoff Berryb96d3b22016-06-01 21:30:40 +0000814char MemorySSAAnalysis::PassID;
George Burgess IVe1100f52016-02-02 22:46:49 +0000815
Geoff Berryb96d3b22016-06-01 21:30:40 +0000816MemorySSA MemorySSAAnalysis::run(Function &F, AnalysisManager<Function> &AM) {
817 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
818 auto &AA = AM.getResult<AAManager>(F);
819 return MemorySSA(F, &AA, &DT);
George Burgess IVe1100f52016-02-02 22:46:49 +0000820}
821
Geoff Berryb96d3b22016-06-01 21:30:40 +0000822PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
823 FunctionAnalysisManager &AM) {
824 OS << "MemorySSA for function: " << F.getName() << "\n";
825 AM.getResult<MemorySSAAnalysis>(F).print(OS);
826
827 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +0000828}
829
Geoff Berryb96d3b22016-06-01 21:30:40 +0000830PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
831 FunctionAnalysisManager &AM) {
832 AM.getResult<MemorySSAAnalysis>(F).verifyMemorySSA();
833
834 return PreservedAnalyses::all();
835}
836
837char MemorySSAWrapperPass::ID = 0;
838
839MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
840 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
841}
842
843void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
844
845void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +0000846 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +0000847 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
848 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +0000849}
850
Geoff Berryb96d3b22016-06-01 21:30:40 +0000851bool MemorySSAWrapperPass::runOnFunction(Function &F) {
852 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
853 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
854 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +0000855 return false;
856}
857
Geoff Berryb96d3b22016-06-01 21:30:40 +0000858void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +0000859
Geoff Berryb96d3b22016-06-01 21:30:40 +0000860void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +0000861 MSSA->print(OS);
862}
863
George Burgess IVe1100f52016-02-02 22:46:49 +0000864MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
865
866CachingMemorySSAWalker::CachingMemorySSAWalker(MemorySSA *M, AliasAnalysis *A,
867 DominatorTree *D)
868 : MemorySSAWalker(M), AA(A), DT(D) {}
869
870CachingMemorySSAWalker::~CachingMemorySSAWalker() {}
871
872struct CachingMemorySSAWalker::UpwardsMemoryQuery {
873 // True if we saw a phi whose predecessor was a backedge
874 bool SawBackedgePhi;
875 // True if our original query started off as a call
876 bool IsCall;
877 // The pointer location we started the query with. This will be empty if
878 // IsCall is true.
879 MemoryLocation StartingLoc;
880 // This is the instruction we were querying about.
881 const Instruction *Inst;
882 // Set of visited Instructions for this query.
883 DenseSet<MemoryAccessPair> Visited;
George Burgess IV49cad7d2016-03-30 03:12:08 +0000884 // Vector of visited call accesses for this query. This is separated out
885 // because you can always cache and lookup the result of call queries (IE when
886 // IsCall == true) for every call in the chain. The calls have no AA location
George Burgess IVe1100f52016-02-02 22:46:49 +0000887 // associated with them with them, and thus, no context dependence.
George Burgess IV49cad7d2016-03-30 03:12:08 +0000888 SmallVector<const MemoryAccess *, 32> VisitedCalls;
George Burgess IVe1100f52016-02-02 22:46:49 +0000889 // The MemoryAccess we actually got called with, used to test local domination
890 const MemoryAccess *OriginalAccess;
891 // The Datalayout for the module we started in
892 const DataLayout *DL;
893
894 UpwardsMemoryQuery()
895 : SawBackedgePhi(false), IsCall(false), Inst(nullptr),
896 OriginalAccess(nullptr), DL(nullptr) {}
897};
898
Daniel Berlin83fc77b2016-03-01 18:46:54 +0000899void CachingMemorySSAWalker::invalidateInfo(MemoryAccess *MA) {
900
901 // TODO: We can do much better cache invalidation with differently stored
902 // caches. For now, for MemoryUses, we simply remove them
903 // from the cache, and kill the entire call/non-call cache for everything
904 // else. The problem is for phis or defs, currently we'd need to follow use
905 // chains down and invalidate anything below us in the chain that currently
906 // terminates at this access.
907
908 // See if this is a MemoryUse, if so, just remove the cached info. MemoryUse
909 // is by definition never a barrier, so nothing in the cache could point to
910 // this use. In that case, we only need invalidate the info for the use
911 // itself.
912
913 if (MemoryUse *MU = dyn_cast<MemoryUse>(MA)) {
914 UpwardsMemoryQuery Q;
915 Instruction *I = MU->getMemoryInst();
916 Q.IsCall = bool(ImmutableCallSite(I));
917 Q.Inst = I;
918 if (!Q.IsCall)
919 Q.StartingLoc = MemoryLocation::get(I);
920 doCacheRemove(MA, Q, Q.StartingLoc);
Geoff Berry9fe26e62016-04-22 14:44:10 +0000921 } else {
922 // If it is not a use, the best we can do right now is destroy the cache.
Daniel Berlin83fc77b2016-03-01 18:46:54 +0000923 CachedUpwardsClobberingCall.clear();
Daniel Berlin83fc77b2016-03-01 18:46:54 +0000924 CachedUpwardsClobberingAccess.clear();
Geoff Berry9fe26e62016-04-22 14:44:10 +0000925 }
926
Filipe Cabecinhas0da99372016-04-29 15:22:48 +0000927#ifdef EXPENSIVE_CHECKS
Geoff Berry9fe26e62016-04-22 14:44:10 +0000928 // Run this only when expensive checks are enabled.
929 verifyRemoved(MA);
930#endif
Daniel Berlin83fc77b2016-03-01 18:46:54 +0000931}
932
George Burgess IVe1100f52016-02-02 22:46:49 +0000933void CachingMemorySSAWalker::doCacheRemove(const MemoryAccess *M,
934 const UpwardsMemoryQuery &Q,
935 const MemoryLocation &Loc) {
936 if (Q.IsCall)
937 CachedUpwardsClobberingCall.erase(M);
938 else
939 CachedUpwardsClobberingAccess.erase({M, Loc});
940}
941
942void CachingMemorySSAWalker::doCacheInsert(const MemoryAccess *M,
943 MemoryAccess *Result,
944 const UpwardsMemoryQuery &Q,
945 const MemoryLocation &Loc) {
George Burgess IV1b1fef32016-04-29 18:42:55 +0000946 // This is fine for Phis, since there are times where we can't optimize them.
947 // Making a def its own clobber is never correct, though.
948 assert((Result != M || isa<MemoryPhi>(M)) &&
949 "Something can't clobber itself!");
George Burgess IVe1100f52016-02-02 22:46:49 +0000950 ++NumClobberCacheInserts;
951 if (Q.IsCall)
952 CachedUpwardsClobberingCall[M] = Result;
953 else
954 CachedUpwardsClobberingAccess[{M, Loc}] = Result;
955}
956
957MemoryAccess *CachingMemorySSAWalker::doCacheLookup(const MemoryAccess *M,
958 const UpwardsMemoryQuery &Q,
959 const MemoryLocation &Loc) {
960 ++NumClobberCacheLookups;
961 MemoryAccess *Result = nullptr;
962
963 if (Q.IsCall)
964 Result = CachedUpwardsClobberingCall.lookup(M);
965 else
966 Result = CachedUpwardsClobberingAccess.lookup({M, Loc});
967
968 if (Result)
969 ++NumClobberCacheHits;
970 return Result;
971}
972
973bool CachingMemorySSAWalker::instructionClobbersQuery(
974 const MemoryDef *MD, UpwardsMemoryQuery &Q,
975 const MemoryLocation &Loc) const {
976 Instruction *DefMemoryInst = MD->getMemoryInst();
977 assert(DefMemoryInst && "Defining instruction not actually an instruction");
978
979 if (!Q.IsCall)
980 return AA->getModRefInfo(DefMemoryInst, Loc) & MRI_Mod;
981
982 // If this is a call, mark it for caching
983 if (ImmutableCallSite(DefMemoryInst))
George Burgess IV49cad7d2016-03-30 03:12:08 +0000984 Q.VisitedCalls.push_back(MD);
George Burgess IVe1100f52016-02-02 22:46:49 +0000985 ModRefInfo I = AA->getModRefInfo(DefMemoryInst, ImmutableCallSite(Q.Inst));
986 return I != MRI_NoModRef;
987}
988
989MemoryAccessPair CachingMemorySSAWalker::UpwardsDFSWalk(
990 MemoryAccess *StartingAccess, const MemoryLocation &Loc,
991 UpwardsMemoryQuery &Q, bool FollowingBackedge) {
992 MemoryAccess *ModifyingAccess = nullptr;
993
994 auto DFI = df_begin(StartingAccess);
995 for (auto DFE = df_end(StartingAccess); DFI != DFE;) {
996 MemoryAccess *CurrAccess = *DFI;
997 if (MSSA->isLiveOnEntryDef(CurrAccess))
998 return {CurrAccess, Loc};
George Burgess IV1b1fef32016-04-29 18:42:55 +0000999 // If this is a MemoryDef, check whether it clobbers our current query. This
1000 // needs to be done before consulting the cache, because the cache reports
1001 // the clobber for CurrAccess. If CurrAccess is a clobber for this query,
1002 // and we ask the cache for information first, then we might skip this
1003 // clobber, which is bad.
George Burgess IVe1100f52016-02-02 22:46:49 +00001004 if (auto *MD = dyn_cast<MemoryDef>(CurrAccess)) {
1005 // If we hit the top, stop following this path.
1006 // While we can do lookups, we can't sanely do inserts here unless we were
1007 // to track everything we saw along the way, since we don't know where we
1008 // will stop.
1009 if (instructionClobbersQuery(MD, Q, Loc)) {
1010 ModifyingAccess = CurrAccess;
1011 break;
1012 }
1013 }
George Burgess IV1b1fef32016-04-29 18:42:55 +00001014 if (auto CacheResult = doCacheLookup(CurrAccess, Q, Loc))
1015 return {CacheResult, Loc};
George Burgess IVe1100f52016-02-02 22:46:49 +00001016
1017 // We need to know whether it is a phi so we can track backedges.
1018 // Otherwise, walk all upward defs.
1019 if (!isa<MemoryPhi>(CurrAccess)) {
1020 ++DFI;
1021 continue;
1022 }
1023
George Burgess IV0e489862016-03-23 18:31:55 +00001024#ifndef NDEBUG
1025 // The loop below visits the phi's children for us. Because phis are the
1026 // only things with multiple edges, skipping the children should always lead
1027 // us to the end of the loop.
1028 //
1029 // Use a copy of DFI because skipChildren would kill our search stack, which
1030 // would make caching anything on the way back impossible.
1031 auto DFICopy = DFI;
1032 assert(DFICopy.skipChildren() == DFE &&
1033 "Skipping phi's children doesn't end the DFS?");
1034#endif
1035
George Burgess IV82ee9422016-03-30 00:26:26 +00001036 const MemoryAccessPair PHIPair(CurrAccess, Loc);
1037
1038 // Don't try to optimize this phi again if we've already tried to do so.
1039 if (!Q.Visited.insert(PHIPair).second) {
1040 ModifyingAccess = CurrAccess;
1041 break;
1042 }
1043
George Burgess IV49cad7d2016-03-30 03:12:08 +00001044 std::size_t InitialVisitedCallSize = Q.VisitedCalls.size();
1045
George Burgess IVe1100f52016-02-02 22:46:49 +00001046 // Recurse on PHI nodes, since we need to change locations.
1047 // TODO: Allow graphtraits on pairs, which would turn this whole function
1048 // into a normal single depth first walk.
1049 MemoryAccess *FirstDef = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001050 for (auto MPI = upward_defs_begin(PHIPair), MPE = upward_defs_end();
1051 MPI != MPE; ++MPI) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001052 bool Backedge =
1053 !FollowingBackedge &&
1054 DT->dominates(CurrAccess->getBlock(), MPI.getPhiArgBlock());
1055
1056 MemoryAccessPair CurrentPair =
1057 UpwardsDFSWalk(MPI->first, MPI->second, Q, Backedge);
1058 // All the phi arguments should reach the same point if we can bypass
1059 // this phi. The alternative is that they hit this phi node, which
1060 // means we can skip this argument.
1061 if (FirstDef && CurrentPair.first != PHIPair.first &&
1062 CurrentPair.first != FirstDef) {
1063 ModifyingAccess = CurrAccess;
1064 break;
1065 }
1066
1067 if (!FirstDef)
1068 FirstDef = CurrentPair.first;
George Burgess IVe1100f52016-02-02 22:46:49 +00001069 }
1070
George Burgess IV0e489862016-03-23 18:31:55 +00001071 // If we exited the loop early, go with the result it gave us.
1072 if (!ModifyingAccess) {
George Burgess IV82ee9422016-03-30 00:26:26 +00001073 assert(FirstDef && "Found a Phi with no upward defs?");
1074 ModifyingAccess = FirstDef;
George Burgess IV49cad7d2016-03-30 03:12:08 +00001075 } else {
1076 // If we can't optimize this Phi, then we can't safely cache any of the
1077 // calls we visited when trying to optimize it. Wipe them out now.
1078 Q.VisitedCalls.resize(InitialVisitedCallSize);
George Burgess IV0e489862016-03-23 18:31:55 +00001079 }
1080 break;
George Burgess IVe1100f52016-02-02 22:46:49 +00001081 }
1082
1083 if (!ModifyingAccess)
1084 return {MSSA->getLiveOnEntryDef(), Q.StartingLoc};
1085
George Burgess IV0e489862016-03-23 18:31:55 +00001086 const BasicBlock *OriginalBlock = StartingAccess->getBlock();
George Burgess IV1b1fef32016-04-29 18:42:55 +00001087 assert(DFI.getPathLength() > 0 && "We dropped our path?");
George Burgess IVe1100f52016-02-02 22:46:49 +00001088 unsigned N = DFI.getPathLength();
George Burgess IV1b1fef32016-04-29 18:42:55 +00001089 // If we found a clobbering def, the last element in the path will be our
1090 // clobber, so we don't want to cache that to itself. OTOH, if we optimized a
1091 // phi, we can add the last thing in the path to the cache, since that won't
1092 // be the result.
1093 if (DFI.getPath(N - 1) == ModifyingAccess)
1094 --N;
1095 for (; N > 1; --N) {
George Burgess IV0e489862016-03-23 18:31:55 +00001096 MemoryAccess *CacheAccess = DFI.getPath(N - 1);
1097 BasicBlock *CurrBlock = CacheAccess->getBlock();
George Burgess IVe1100f52016-02-02 22:46:49 +00001098 if (!FollowingBackedge)
George Burgess IV0e489862016-03-23 18:31:55 +00001099 doCacheInsert(CacheAccess, ModifyingAccess, Q, Loc);
George Burgess IVe1100f52016-02-02 22:46:49 +00001100 if (DT->dominates(CurrBlock, OriginalBlock) &&
1101 (CurrBlock != OriginalBlock || !FollowingBackedge ||
George Burgess IV0e489862016-03-23 18:31:55 +00001102 MSSA->locallyDominates(CacheAccess, StartingAccess)))
George Burgess IVe1100f52016-02-02 22:46:49 +00001103 break;
1104 }
1105
1106 // Cache everything else on the way back. The caller should cache
George Burgess IV1b1fef32016-04-29 18:42:55 +00001107 // StartingAccess for us.
1108 for (; N > 1; --N) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001109 MemoryAccess *CacheAccess = DFI.getPath(N - 1);
1110 doCacheInsert(CacheAccess, ModifyingAccess, Q, Loc);
1111 }
1112 assert(Q.Visited.size() < 1000 && "Visited too much");
1113
1114 return {ModifyingAccess, Loc};
1115}
1116
1117/// \brief Walk the use-def chains starting at \p MA and find
1118/// the MemoryAccess that actually clobbers Loc.
1119///
1120/// \returns our clobbering memory access
1121MemoryAccess *
1122CachingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *StartingAccess,
1123 UpwardsMemoryQuery &Q) {
1124 return UpwardsDFSWalk(StartingAccess, Q.StartingLoc, Q, false).first;
1125}
1126
1127MemoryAccess *
1128CachingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *StartingAccess,
1129 MemoryLocation &Loc) {
1130 if (isa<MemoryPhi>(StartingAccess))
1131 return StartingAccess;
1132
1133 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
1134 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
1135 return StartingUseOrDef;
1136
1137 Instruction *I = StartingUseOrDef->getMemoryInst();
1138
1139 // Conservatively, fences are always clobbers, so don't perform the walk if we
1140 // hit a fence.
1141 if (isa<FenceInst>(I))
1142 return StartingUseOrDef;
1143
1144 UpwardsMemoryQuery Q;
1145 Q.OriginalAccess = StartingUseOrDef;
1146 Q.StartingLoc = Loc;
1147 Q.Inst = StartingUseOrDef->getMemoryInst();
1148 Q.IsCall = false;
1149 Q.DL = &Q.Inst->getModule()->getDataLayout();
1150
1151 if (auto CacheResult = doCacheLookup(StartingUseOrDef, Q, Q.StartingLoc))
1152 return CacheResult;
1153
1154 // Unlike the other function, do not walk to the def of a def, because we are
1155 // handed something we already believe is the clobbering access.
1156 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
1157 ? StartingUseOrDef->getDefiningAccess()
1158 : StartingUseOrDef;
1159
1160 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IV1b1fef32016-04-29 18:42:55 +00001161 // Only cache this if it wouldn't make Clobber point to itself.
1162 if (Clobber != StartingAccess)
1163 doCacheInsert(Q.OriginalAccess, Clobber, Q, Q.StartingLoc);
George Burgess IVe1100f52016-02-02 22:46:49 +00001164 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
1165 DEBUG(dbgs() << *StartingUseOrDef << "\n");
1166 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
1167 DEBUG(dbgs() << *Clobber << "\n");
1168 return Clobber;
1169}
1170
1171MemoryAccess *
1172CachingMemorySSAWalker::getClobberingMemoryAccess(const Instruction *I) {
1173 // There should be no way to lookup an instruction and get a phi as the
1174 // access, since we only map BB's to PHI's. So, this must be a use or def.
1175 auto *StartingAccess = cast<MemoryUseOrDef>(MSSA->getMemoryAccess(I));
1176
1177 // We can't sanely do anything with a FenceInst, they conservatively
1178 // clobber all memory, and have no locations to get pointers from to
1179 // try to disambiguate
1180 if (isa<FenceInst>(I))
1181 return StartingAccess;
1182
1183 UpwardsMemoryQuery Q;
1184 Q.OriginalAccess = StartingAccess;
1185 Q.IsCall = bool(ImmutableCallSite(I));
1186 if (!Q.IsCall)
1187 Q.StartingLoc = MemoryLocation::get(I);
1188 Q.Inst = I;
1189 Q.DL = &Q.Inst->getModule()->getDataLayout();
1190 if (auto CacheResult = doCacheLookup(StartingAccess, Q, Q.StartingLoc))
1191 return CacheResult;
1192
1193 // Start with the thing we already think clobbers this location
1194 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
1195
1196 // At this point, DefiningAccess may be the live on entry def.
1197 // If it is, we will not get a better result.
1198 if (MSSA->isLiveOnEntryDef(DefiningAccess))
1199 return DefiningAccess;
1200
1201 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IV1b1fef32016-04-29 18:42:55 +00001202 // DFS won't cache a result for DefiningAccess. So, if DefiningAccess isn't
1203 // our clobber, be sure that it gets a cache entry, too.
1204 if (Result != DefiningAccess)
1205 doCacheInsert(DefiningAccess, Result, Q, Q.StartingLoc);
George Burgess IVe1100f52016-02-02 22:46:49 +00001206 doCacheInsert(Q.OriginalAccess, Result, Q, Q.StartingLoc);
1207 // TODO: When this implementation is more mature, we may want to figure out
1208 // what this additional caching buys us. It's most likely A Good Thing.
1209 if (Q.IsCall)
1210 for (const MemoryAccess *MA : Q.VisitedCalls)
George Burgess IV1b1fef32016-04-29 18:42:55 +00001211 if (MA != Result)
1212 doCacheInsert(MA, Result, Q, Q.StartingLoc);
George Burgess IVe1100f52016-02-02 22:46:49 +00001213
1214 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
1215 DEBUG(dbgs() << *DefiningAccess << "\n");
1216 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
1217 DEBUG(dbgs() << *Result << "\n");
1218
1219 return Result;
1220}
1221
Geoff Berry9fe26e62016-04-22 14:44:10 +00001222// Verify that MA doesn't exist in any of the caches.
1223void CachingMemorySSAWalker::verifyRemoved(MemoryAccess *MA) {
1224#ifndef NDEBUG
1225 for (auto &P : CachedUpwardsClobberingAccess)
1226 assert(P.first.first != MA && P.second != MA &&
1227 "Found removed MemoryAccess in cache.");
1228 for (auto &P : CachedUpwardsClobberingCall)
1229 assert(P.first != MA && P.second != MA &&
1230 "Found removed MemoryAccess in cache.");
1231#endif // !NDEBUG
1232}
1233
George Burgess IVe1100f52016-02-02 22:46:49 +00001234MemoryAccess *
1235DoNothingMemorySSAWalker::getClobberingMemoryAccess(const Instruction *I) {
1236 MemoryAccess *MA = MSSA->getMemoryAccess(I);
1237 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
1238 return Use->getDefiningAccess();
1239 return MA;
1240}
1241
1242MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
1243 MemoryAccess *StartingAccess, MemoryLocation &) {
1244 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
1245 return Use->getDefiningAccess();
1246 return StartingAccess;
1247}
1248}