blob: 382a18b025a51890e4966359fbd42a433730fdea [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//===----------------------------------------------------------------===//
13#include "llvm/ADT/DenseMap.h"
14#include "llvm/ADT/DenseSet.h"
15#include "llvm/ADT/DepthFirstIterator.h"
16#include "llvm/ADT/GraphTraits.h"
17#include "llvm/ADT/PostOrderIterator.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/SmallSet.h"
21#include "llvm/ADT/Statistic.h"
22#include "llvm/Analysis/AliasAnalysis.h"
23#include "llvm/Analysis/CFG.h"
24#include "llvm/Analysis/GlobalsModRef.h"
25#include "llvm/Analysis/IteratedDominanceFrontier.h"
26#include "llvm/Analysis/MemoryLocation.h"
27#include "llvm/Analysis/PHITransAddr.h"
28#include "llvm/IR/AssemblyAnnotationWriter.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Dominators.h"
31#include "llvm/IR/GlobalVariable.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/Metadata.h"
36#include "llvm/IR/Module.h"
37#include "llvm/IR/PatternMatch.h"
38#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/Debug.h"
40#include "llvm/Support/FormattedStream.h"
41#include "llvm/Transforms/Scalar.h"
42#include "llvm/Transforms/Utils/MemorySSA.h"
43#include <algorithm>
44
45#define DEBUG_TYPE "memoryssa"
46using namespace llvm;
47STATISTIC(NumClobberCacheLookups, "Number of Memory SSA version cache lookups");
48STATISTIC(NumClobberCacheHits, "Number of Memory SSA version cache hits");
49STATISTIC(NumClobberCacheInserts, "Number of MemorySSA version cache inserts");
50INITIALIZE_PASS_WITH_OPTIONS_BEGIN(MemorySSAPrinterPass, "print-memoryssa",
51 "Memory SSA", true, true)
52INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
53INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
54INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
55INITIALIZE_PASS_END(MemorySSAPrinterPass, "print-memoryssa", "Memory SSA", true,
56 true)
57INITIALIZE_PASS(MemorySSALazy, "memoryssalazy", "Memory SSA", true, true)
58
59namespace llvm {
60
61/// \brief An assembly annotator class to print Memory SSA information in
62/// comments.
63class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
64 friend class MemorySSA;
65 const MemorySSA *MSSA;
66
67public:
68 MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
69
70 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
71 formatted_raw_ostream &OS) {
72 if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
73 OS << "; " << *MA << "\n";
74 }
75
76 virtual void emitInstructionAnnot(const Instruction *I,
77 formatted_raw_ostream &OS) {
78 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
79 OS << "; " << *MA << "\n";
80 }
81};
82}
83
84namespace {
85struct RenamePassData {
86 DomTreeNode *DTN;
87 DomTreeNode::const_iterator ChildIt;
88 MemoryAccess *IncomingVal;
89
90 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
91 MemoryAccess *M)
92 : DTN(D), ChildIt(It), IncomingVal(M) {}
93 void swap(RenamePassData &RHS) {
94 std::swap(DTN, RHS.DTN);
95 std::swap(ChildIt, RHS.ChildIt);
96 std::swap(IncomingVal, RHS.IncomingVal);
97 }
98};
99}
100
101namespace llvm {
102/// \brief Rename a single basic block into MemorySSA form.
103/// Uses the standard SSA renaming algorithm.
104/// \returns The new incoming value.
105MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB,
106 MemoryAccess *IncomingVal) {
107 auto It = PerBlockAccesses.find(BB);
108 // Skip most processing if the list is empty.
109 if (It != PerBlockAccesses.end()) {
110 AccessListType *Accesses = It->second.get();
111 for (MemoryAccess &L : *Accesses) {
112 switch (L.getValueID()) {
113 case Value::MemoryUseVal:
114 cast<MemoryUse>(&L)->setDefiningAccess(IncomingVal);
115 break;
116 case Value::MemoryDefVal:
117 // We can't legally optimize defs, because we only allow single
118 // memory phis/uses on operations, and if we optimize these, we can
119 // end up with multiple reaching defs. Uses do not have this
120 // problem, since they do not produce a value
121 cast<MemoryDef>(&L)->setDefiningAccess(IncomingVal);
122 IncomingVal = &L;
123 break;
124 case Value::MemoryPhiVal:
125 IncomingVal = &L;
126 break;
127 }
128 }
129 }
130
131 // Pass through values to our successors
132 for (const BasicBlock *S : successors(BB)) {
133 auto It = PerBlockAccesses.find(S);
134 // Rename the phi nodes in our successor block
135 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
136 continue;
137 AccessListType *Accesses = It->second.get();
138 auto *Phi = cast<MemoryPhi>(&Accesses->front());
139 assert(std::find(succ_begin(BB), succ_end(BB), S) != succ_end(BB) &&
140 "Must be at least one edge from Succ to BB!");
141 Phi->addIncoming(IncomingVal, BB);
142 }
143
144 return IncomingVal;
145}
146
147/// \brief This is the standard SSA renaming algorithm.
148///
149/// We walk the dominator tree in preorder, renaming accesses, and then filling
150/// in phi nodes in our successors.
151void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
152 SmallPtrSet<BasicBlock *, 16> &Visited) {
153 SmallVector<RenamePassData, 32> WorkStack;
154 IncomingVal = renameBlock(Root->getBlock(), IncomingVal);
155 WorkStack.push_back({Root, Root->begin(), IncomingVal});
156 Visited.insert(Root->getBlock());
157
158 while (!WorkStack.empty()) {
159 DomTreeNode *Node = WorkStack.back().DTN;
160 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
161 IncomingVal = WorkStack.back().IncomingVal;
162
163 if (ChildIt == Node->end()) {
164 WorkStack.pop_back();
165 } else {
166 DomTreeNode *Child = *ChildIt;
167 ++WorkStack.back().ChildIt;
168 BasicBlock *BB = Child->getBlock();
169 Visited.insert(BB);
170 IncomingVal = renameBlock(BB, IncomingVal);
171 WorkStack.push_back({Child, Child->begin(), IncomingVal});
172 }
173 }
174}
175
176/// \brief Compute dominator levels, used by the phi insertion algorithm above.
177void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) {
178 for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode());
179 DFI != DFE; ++DFI)
180 DomLevels[*DFI] = DFI.getPathLength() - 1;
181}
182
183/// \brief This handles unreachable block acccesses by deleting phi nodes in
184/// unreachable blocks, and marking all other unreachable MemoryAccess's as
185/// being uses of the live on entry definition.
186void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
187 assert(!DT->isReachableFromEntry(BB) &&
188 "Reachable block found while handling unreachable blocks");
189
190 auto It = PerBlockAccesses.find(BB);
191 if (It == PerBlockAccesses.end())
192 return;
193
194 auto &Accesses = It->second;
195 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
196 auto Next = std::next(AI);
197 // If we have a phi, just remove it. We are going to replace all
198 // users with live on entry.
199 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
200 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
201 else
202 Accesses->erase(AI);
203 AI = Next;
204 }
205}
206
207MemorySSA::MemorySSA(Function &Func)
208 : AA(nullptr), DT(nullptr), F(Func), LiveOnEntryDef(nullptr),
209 Walker(nullptr), NextID(0) {}
210
211MemorySSA::~MemorySSA() {
212 // Drop all our references
213 for (const auto &Pair : PerBlockAccesses)
214 for (MemoryAccess &MA : *Pair.second)
215 MA.dropAllReferences();
216}
217
218MemorySSA::AccessListType *MemorySSA::getOrCreateAccessList(BasicBlock *BB) {
219 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
220
221 if (Res.second)
222 Res.first->second = make_unique<AccessListType>();
223 return Res.first->second.get();
224}
225
226MemorySSAWalker *MemorySSA::buildMemorySSA(AliasAnalysis *AA,
227 DominatorTree *DT) {
228 if (Walker)
229 return Walker;
230
231 assert(!this->AA && !this->DT &&
232 "MemorySSA without a walker already has AA or DT?");
233
234 auto *Result = new CachingMemorySSAWalker(this, AA, DT);
235 this->AA = AA;
236 this->DT = DT;
237
238 // We create an access to represent "live on entry", for things like
239 // arguments or users of globals, where the memory they use is defined before
240 // the beginning of the function. We do not actually insert it into the IR.
241 // We do not define a live on exit for the immediate uses, and thus our
242 // semantics do *not* imply that something with no immediate uses can simply
243 // be removed.
244 BasicBlock &StartingPoint = F.getEntryBlock();
245 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
246 &StartingPoint, NextID++);
247
248 // We maintain lists of memory accesses per-block, trading memory for time. We
249 // could just look up the memory access for every possible instruction in the
250 // stream.
251 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
252
253 // Go through each block, figure out where defs occur, and chain together all
254 // the accesses.
255 for (BasicBlock &B : F) {
256 AccessListType *Accesses = nullptr;
257 for (Instruction &I : B) {
258 MemoryAccess *MA = createNewAccess(&I, true);
259 if (!MA)
260 continue;
261 if (isa<MemoryDef>(MA))
262 DefiningBlocks.insert(&B);
263 if (!Accesses)
264 Accesses = getOrCreateAccessList(&B);
265 Accesses->push_back(MA);
266 }
267 }
268
269 // Determine where our MemoryPhi's should go
270 IDFCalculator IDFs(*DT);
271 IDFs.setDefiningBlocks(DefiningBlocks);
272 SmallVector<BasicBlock *, 32> IDFBlocks;
273 IDFs.calculate(IDFBlocks);
274
275 // Now place MemoryPhi nodes.
276 for (auto &BB : IDFBlocks) {
277 // Insert phi node
278 AccessListType *Accesses = getOrCreateAccessList(BB);
279 MemoryPhi *Phi = new MemoryPhi(F.getContext(), BB, NextID++);
280 InstructionToMemoryAccess.insert(std::make_pair(BB, Phi));
281 // Phi's always are placed at the front of the block.
282 Accesses->push_front(Phi);
283 }
284
285 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
286 // filled in with all blocks.
287 SmallPtrSet<BasicBlock *, 16> Visited;
288 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
289
290 // Now optimize the MemoryUse's defining access to point to the nearest
291 // dominating clobbering def.
292 // This ensures that MemoryUse's that are killed by the same store are
293 // immediate users of that store, one of the invariants we guarantee.
294 for (auto DomNode : depth_first(DT)) {
295 BasicBlock *BB = DomNode->getBlock();
296 auto AI = PerBlockAccesses.find(BB);
297 if (AI == PerBlockAccesses.end())
298 continue;
299 AccessListType *Accesses = AI->second.get();
300 for (auto &MA : *Accesses) {
301 if (auto *MU = dyn_cast<MemoryUse>(&MA)) {
302 Instruction *Inst = MU->getMemoryInst();
303 MU->setDefiningAccess(Result->getClobberingMemoryAccess(Inst));
304 }
305 }
306 }
307
308 // Mark the uses in unreachable blocks as live on entry, so that they go
309 // somewhere.
310 for (auto &BB : F)
311 if (!Visited.count(&BB))
312 markUnreachableAsLiveOnEntry(&BB);
313
314 Walker = Result;
315 return Walker;
316}
317
318/// \brief Helper function to create new memory accesses
319MemoryAccess *MemorySSA::createNewAccess(Instruction *I, bool IgnoreNonMemory) {
320 // Find out what affect this instruction has on memory.
321 ModRefInfo ModRef = AA->getModRefInfo(I);
322 bool Def = bool(ModRef & MRI_Mod);
323 bool Use = bool(ModRef & MRI_Ref);
324
325 // It's possible for an instruction to not modify memory at all. During
326 // construction, we ignore them.
327 if (IgnoreNonMemory && !Def && !Use)
328 return nullptr;
329
330 assert((Def || Use) &&
331 "Trying to create a memory access with a non-memory instruction");
332
333 MemoryUseOrDef *MA;
334 if (Def)
335 MA = new MemoryDef(I->getModule()->getContext(), nullptr, I, I->getParent(),
336 NextID++);
337 else
338 MA =
339 new MemoryUse(I->getModule()->getContext(), nullptr, I, I->getParent());
340 InstructionToMemoryAccess.insert(std::make_pair(I, MA));
341 return MA;
342}
343
344MemoryAccess *MemorySSA::findDominatingDef(BasicBlock *UseBlock,
345 enum InsertionPlace Where) {
346 // Handle the initial case
347 if (Where == Beginning)
348 // The only thing that could define us at the beginning is a phi node
349 if (MemoryPhi *Phi = getMemoryAccess(UseBlock))
350 return Phi;
351
352 DomTreeNode *CurrNode = DT->getNode(UseBlock);
353 // Need to be defined by our dominator
354 if (Where == Beginning)
355 CurrNode = CurrNode->getIDom();
356 Where = End;
357 while (CurrNode) {
358 auto It = PerBlockAccesses.find(CurrNode->getBlock());
359 if (It != PerBlockAccesses.end()) {
360 auto &Accesses = It->second;
361 for (auto RAI = Accesses->rbegin(), RAE = Accesses->rend(); RAI != RAE;
362 ++RAI) {
363 if (isa<MemoryDef>(*RAI) || isa<MemoryPhi>(*RAI))
364 return &*RAI;
365 }
366 }
367 CurrNode = CurrNode->getIDom();
368 }
369 return LiveOnEntryDef.get();
370}
371
372/// \brief Returns true if \p Replacer dominates \p Replacee .
373bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
374 const MemoryAccess *Replacee) const {
375 if (isa<MemoryUseOrDef>(Replacee))
376 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
377 const auto *MP = cast<MemoryPhi>(Replacee);
378 // For a phi node, the use occurs in the predecessor block of the phi node.
379 // Since we may occur multiple times in the phi node, we have to check each
380 // operand to ensure Replacer dominates each operand where Replacee occurs.
381 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +0000382 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +0000383 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
384 return false;
385 }
386 return true;
387}
388
389void MemorySSA::print(raw_ostream &OS) const {
390 MemorySSAAnnotatedWriter Writer(this);
391 F.print(OS, &Writer);
392}
393
394void MemorySSA::dump() const {
395 MemorySSAAnnotatedWriter Writer(this);
396 F.print(dbgs(), &Writer);
397}
398
399/// \brief Verify the domination properties of MemorySSA by checking that each
400/// definition dominates all of its uses.
401void MemorySSA::verifyDomination(Function &F) {
402 for (BasicBlock &B : F) {
403 // Phi nodes are attached to basic blocks
404 if (MemoryPhi *MP = getMemoryAccess(&B)) {
405 for (User *U : MP->users()) {
406 BasicBlock *UseBlock;
407 // Phi operands are used on edges, we simulate the right domination by
408 // acting as if the use occurred at the end of the predecessor block.
409 if (MemoryPhi *P = dyn_cast<MemoryPhi>(U)) {
410 for (const auto &Arg : P->operands()) {
411 if (Arg == MP) {
412 UseBlock = P->getIncomingBlock(Arg);
413 break;
414 }
415 }
416 } else {
417 UseBlock = cast<MemoryAccess>(U)->getBlock();
418 }
George Burgess IV60adac42016-02-02 23:26:01 +0000419 (void)UseBlock;
George Burgess IVe1100f52016-02-02 22:46:49 +0000420 assert(DT->dominates(MP->getBlock(), UseBlock) &&
421 "Memory PHI does not dominate it's uses");
422 }
423 }
424
425 for (Instruction &I : B) {
426 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
427 if (!MD)
428 continue;
429
430 for (const auto &U : MD->users()) {
431 BasicBlock *UseBlock;
432 // Things are allowed to flow to phi nodes over their predecessor edge.
433 if (auto *P = dyn_cast<MemoryPhi>(U)) {
434 for (const auto &Arg : P->operands()) {
435 if (Arg == MD) {
436 UseBlock = P->getIncomingBlock(Arg);
437 break;
438 }
439 }
440 } else {
441 UseBlock = cast<MemoryAccess>(U)->getBlock();
442 }
443 assert(DT->dominates(MD->getBlock(), UseBlock) &&
444 "Memory Def does not dominate it's uses");
445 }
446 }
447 }
448}
449
450/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
451/// appears in the use list of \p Def.
452///
453/// llvm_unreachable is used instead of asserts because this may be called in
454/// a build without asserts. In that case, we don't want this to turn into a
455/// nop.
456void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) {
457 // The live on entry use may cause us to get a NULL def here
458 if (!Def) {
459 if (!isLiveOnEntryDef(Use))
460 llvm_unreachable("Null def but use not point to live on entry def");
461 } else if (std::find(Def->user_begin(), Def->user_end(), Use) ==
462 Def->user_end()) {
463 llvm_unreachable("Did not find use in def's use list");
464 }
465}
466
467/// \brief Verify the immediate use information, by walking all the memory
468/// accesses and verifying that, for each use, it appears in the
469/// appropriate def's use list
470void MemorySSA::verifyDefUses(Function &F) {
471 for (BasicBlock &B : F) {
472 // Phi nodes are attached to basic blocks
473 if (MemoryPhi *Phi = getMemoryAccess(&B))
474 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
475 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
476
477 for (Instruction &I : B) {
478 if (MemoryAccess *MA = getMemoryAccess(&I)) {
479 assert(isa<MemoryUseOrDef>(MA) &&
480 "Found a phi node not attached to a bb");
481 verifyUseInDefs(cast<MemoryUseOrDef>(MA)->getDefiningAccess(), MA);
482 }
483 }
484 }
485}
486
487MemoryAccess *MemorySSA::getMemoryAccess(const Value *I) const {
488 return InstructionToMemoryAccess.lookup(I);
489}
490
491MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
492 return cast_or_null<MemoryPhi>(getMemoryAccess((const Value *)BB));
493}
494
495/// \brief Determine, for two memory accesses in the same block,
496/// whether \p Dominator dominates \p Dominatee.
497/// \returns True if \p Dominator dominates \p Dominatee.
498bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
499 const MemoryAccess *Dominatee) const {
500
501 assert((Dominator->getBlock() == Dominatee->getBlock()) &&
502 "Asking for local domination when accesses are in different blocks!");
503 // Get the access list for the block
504 const AccessListType *AccessList = getBlockAccesses(Dominator->getBlock());
505 AccessListType::const_reverse_iterator It(Dominator->getIterator());
506
507 // If we hit the beginning of the access list before we hit dominatee, we must
508 // dominate it
509 return std::none_of(It, AccessList->rend(),
510 [&](const MemoryAccess &MA) { return &MA == Dominatee; });
511}
512
513const static char LiveOnEntryStr[] = "liveOnEntry";
514
515void MemoryDef::print(raw_ostream &OS) const {
516 MemoryAccess *UO = getDefiningAccess();
517
518 OS << getID() << " = MemoryDef(";
519 if (UO && UO->getID())
520 OS << UO->getID();
521 else
522 OS << LiveOnEntryStr;
523 OS << ')';
524}
525
526void MemoryPhi::print(raw_ostream &OS) const {
527 bool First = true;
528 OS << getID() << " = MemoryPhi(";
529 for (const auto &Op : operands()) {
530 BasicBlock *BB = getIncomingBlock(Op);
531 MemoryAccess *MA = cast<MemoryAccess>(Op);
532 if (!First)
533 OS << ',';
534 else
535 First = false;
536
537 OS << '{';
538 if (BB->hasName())
539 OS << BB->getName();
540 else
541 BB->printAsOperand(OS, false);
542 OS << ',';
543 if (unsigned ID = MA->getID())
544 OS << ID;
545 else
546 OS << LiveOnEntryStr;
547 OS << '}';
548 }
549 OS << ')';
550}
551
552MemoryAccess::~MemoryAccess() {}
553
554void MemoryUse::print(raw_ostream &OS) const {
555 MemoryAccess *UO = getDefiningAccess();
556 OS << "MemoryUse(";
557 if (UO && UO->getID())
558 OS << UO->getID();
559 else
560 OS << LiveOnEntryStr;
561 OS << ')';
562}
563
564void MemoryAccess::dump() const {
565 print(dbgs());
566 dbgs() << "\n";
567}
568
569char MemorySSAPrinterPass::ID = 0;
570
571MemorySSAPrinterPass::MemorySSAPrinterPass() : FunctionPass(ID) {
572 initializeMemorySSAPrinterPassPass(*PassRegistry::getPassRegistry());
573}
574
575void MemorySSAPrinterPass::releaseMemory() {
576 // Subtlety: Be sure to delete the walker before MSSA, because the walker's
577 // dtor may try to access MemorySSA.
578 Walker.reset();
579 MSSA.reset();
580}
581
582void MemorySSAPrinterPass::getAnalysisUsage(AnalysisUsage &AU) const {
583 AU.setPreservesAll();
584 AU.addRequired<AAResultsWrapperPass>();
585 AU.addRequired<DominatorTreeWrapperPass>();
586 AU.addPreserved<DominatorTreeWrapperPass>();
587 AU.addPreserved<GlobalsAAWrapperPass>();
588}
589
590bool MemorySSAPrinterPass::doInitialization(Module &M) {
George Burgess IV60adac42016-02-02 23:26:01 +0000591 VerifyMemorySSA = M.getContext()
592 .getOption<bool, MemorySSAPrinterPass,
593 &MemorySSAPrinterPass::VerifyMemorySSA>();
George Burgess IVe1100f52016-02-02 22:46:49 +0000594 return false;
595}
596
597void MemorySSAPrinterPass::registerOptions() {
598 OptionRegistry::registerOption<bool, MemorySSAPrinterPass,
599 &MemorySSAPrinterPass::VerifyMemorySSA>(
600 "verify-memoryssa", "Run the Memory SSA verifier", false);
601}
602
603void MemorySSAPrinterPass::print(raw_ostream &OS, const Module *M) const {
604 MSSA->print(OS);
605}
606
607bool MemorySSAPrinterPass::runOnFunction(Function &F) {
608 this->F = &F;
609 MSSA.reset(new MemorySSA(F));
610 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
611 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
612 Walker.reset(MSSA->buildMemorySSA(AA, DT));
613
614 if (VerifyMemorySSA) {
615 MSSA->verifyDefUses(F);
616 MSSA->verifyDomination(F);
617 }
618
619 return false;
620}
621
622char MemorySSALazy::ID = 0;
623
624MemorySSALazy::MemorySSALazy() : FunctionPass(ID) {
625 initializeMemorySSALazyPass(*PassRegistry::getPassRegistry());
626}
627
628void MemorySSALazy::releaseMemory() { MSSA.reset(); }
629
630bool MemorySSALazy::runOnFunction(Function &F) {
631 MSSA.reset(new MemorySSA(F));
632 return false;
633}
634
635MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
636
637CachingMemorySSAWalker::CachingMemorySSAWalker(MemorySSA *M, AliasAnalysis *A,
638 DominatorTree *D)
639 : MemorySSAWalker(M), AA(A), DT(D) {}
640
641CachingMemorySSAWalker::~CachingMemorySSAWalker() {}
642
643struct CachingMemorySSAWalker::UpwardsMemoryQuery {
644 // True if we saw a phi whose predecessor was a backedge
645 bool SawBackedgePhi;
646 // True if our original query started off as a call
647 bool IsCall;
648 // The pointer location we started the query with. This will be empty if
649 // IsCall is true.
650 MemoryLocation StartingLoc;
651 // This is the instruction we were querying about.
652 const Instruction *Inst;
653 // Set of visited Instructions for this query.
654 DenseSet<MemoryAccessPair> Visited;
655 // Set of visited call accesses for this query. This is separated out because
656 // you can always cache and lookup the result of call queries (IE when IsCall
657 // == true) for every call in the chain. The calls have no AA location
658 // associated with them with them, and thus, no context dependence.
659 SmallPtrSet<const MemoryAccess *, 32> VisitedCalls;
660 // The MemoryAccess we actually got called with, used to test local domination
661 const MemoryAccess *OriginalAccess;
662 // The Datalayout for the module we started in
663 const DataLayout *DL;
664
665 UpwardsMemoryQuery()
666 : SawBackedgePhi(false), IsCall(false), Inst(nullptr),
667 OriginalAccess(nullptr), DL(nullptr) {}
668};
669
670void CachingMemorySSAWalker::doCacheRemove(const MemoryAccess *M,
671 const UpwardsMemoryQuery &Q,
672 const MemoryLocation &Loc) {
673 if (Q.IsCall)
674 CachedUpwardsClobberingCall.erase(M);
675 else
676 CachedUpwardsClobberingAccess.erase({M, Loc});
677}
678
679void CachingMemorySSAWalker::doCacheInsert(const MemoryAccess *M,
680 MemoryAccess *Result,
681 const UpwardsMemoryQuery &Q,
682 const MemoryLocation &Loc) {
683 ++NumClobberCacheInserts;
684 if (Q.IsCall)
685 CachedUpwardsClobberingCall[M] = Result;
686 else
687 CachedUpwardsClobberingAccess[{M, Loc}] = Result;
688}
689
690MemoryAccess *CachingMemorySSAWalker::doCacheLookup(const MemoryAccess *M,
691 const UpwardsMemoryQuery &Q,
692 const MemoryLocation &Loc) {
693 ++NumClobberCacheLookups;
694 MemoryAccess *Result = nullptr;
695
696 if (Q.IsCall)
697 Result = CachedUpwardsClobberingCall.lookup(M);
698 else
699 Result = CachedUpwardsClobberingAccess.lookup({M, Loc});
700
701 if (Result)
702 ++NumClobberCacheHits;
703 return Result;
704}
705
706bool CachingMemorySSAWalker::instructionClobbersQuery(
707 const MemoryDef *MD, UpwardsMemoryQuery &Q,
708 const MemoryLocation &Loc) const {
709 Instruction *DefMemoryInst = MD->getMemoryInst();
710 assert(DefMemoryInst && "Defining instruction not actually an instruction");
711
712 if (!Q.IsCall)
713 return AA->getModRefInfo(DefMemoryInst, Loc) & MRI_Mod;
714
715 // If this is a call, mark it for caching
716 if (ImmutableCallSite(DefMemoryInst))
717 Q.VisitedCalls.insert(MD);
718 ModRefInfo I = AA->getModRefInfo(DefMemoryInst, ImmutableCallSite(Q.Inst));
719 return I != MRI_NoModRef;
720}
721
722MemoryAccessPair CachingMemorySSAWalker::UpwardsDFSWalk(
723 MemoryAccess *StartingAccess, const MemoryLocation &Loc,
724 UpwardsMemoryQuery &Q, bool FollowingBackedge) {
725 MemoryAccess *ModifyingAccess = nullptr;
726
727 auto DFI = df_begin(StartingAccess);
728 for (auto DFE = df_end(StartingAccess); DFI != DFE;) {
729 MemoryAccess *CurrAccess = *DFI;
730 if (MSSA->isLiveOnEntryDef(CurrAccess))
731 return {CurrAccess, Loc};
732 if (auto CacheResult = doCacheLookup(CurrAccess, Q, Loc))
733 return {CacheResult, Loc};
734 // If this is a MemoryDef, check whether it clobbers our current query.
735 if (auto *MD = dyn_cast<MemoryDef>(CurrAccess)) {
736 // If we hit the top, stop following this path.
737 // While we can do lookups, we can't sanely do inserts here unless we were
738 // to track everything we saw along the way, since we don't know where we
739 // will stop.
740 if (instructionClobbersQuery(MD, Q, Loc)) {
741 ModifyingAccess = CurrAccess;
742 break;
743 }
744 }
745
746 // We need to know whether it is a phi so we can track backedges.
747 // Otherwise, walk all upward defs.
748 if (!isa<MemoryPhi>(CurrAccess)) {
749 ++DFI;
750 continue;
751 }
752
753 // Recurse on PHI nodes, since we need to change locations.
754 // TODO: Allow graphtraits on pairs, which would turn this whole function
755 // into a normal single depth first walk.
756 MemoryAccess *FirstDef = nullptr;
757 DFI = DFI.skipChildren();
758 const MemoryAccessPair PHIPair(CurrAccess, Loc);
759 bool VisitedOnlyOne = true;
760 for (auto MPI = upward_defs_begin(PHIPair), MPE = upward_defs_end();
761 MPI != MPE; ++MPI) {
762 // Don't follow this path again if we've followed it once
763 if (!Q.Visited.insert(*MPI).second)
764 continue;
765
766 bool Backedge =
767 !FollowingBackedge &&
768 DT->dominates(CurrAccess->getBlock(), MPI.getPhiArgBlock());
769
770 MemoryAccessPair CurrentPair =
771 UpwardsDFSWalk(MPI->first, MPI->second, Q, Backedge);
772 // All the phi arguments should reach the same point if we can bypass
773 // this phi. The alternative is that they hit this phi node, which
774 // means we can skip this argument.
775 if (FirstDef && CurrentPair.first != PHIPair.first &&
776 CurrentPair.first != FirstDef) {
777 ModifyingAccess = CurrAccess;
778 break;
779 }
780
781 if (!FirstDef)
782 FirstDef = CurrentPair.first;
783 else
784 VisitedOnlyOne = false;
785 }
786
787 // The above loop determines if all arguments of the phi node reach the
788 // same place. However we skip arguments that are cyclically dependent
789 // only on the value of this phi node. This means in some cases, we may
790 // only visit one argument of the phi node, and the above loop will
791 // happily say that all the arguments are the same. However, in that case,
792 // we still can't walk past the phi node, because that argument still
793 // kills the access unless we hit the top of the function when walking
794 // that argument.
795 if (VisitedOnlyOne && FirstDef && !MSSA->isLiveOnEntryDef(FirstDef))
796 ModifyingAccess = CurrAccess;
797 }
798
799 if (!ModifyingAccess)
800 return {MSSA->getLiveOnEntryDef(), Q.StartingLoc};
801
802 const BasicBlock *OriginalBlock = Q.OriginalAccess->getBlock();
803 unsigned N = DFI.getPathLength();
804 MemoryAccess *FinalAccess = ModifyingAccess;
805 for (; N != 0; --N) {
806 ModifyingAccess = DFI.getPath(N - 1);
807 BasicBlock *CurrBlock = ModifyingAccess->getBlock();
808 if (!FollowingBackedge)
809 doCacheInsert(ModifyingAccess, FinalAccess, Q, Loc);
810 if (DT->dominates(CurrBlock, OriginalBlock) &&
811 (CurrBlock != OriginalBlock || !FollowingBackedge ||
812 MSSA->locallyDominates(ModifyingAccess, Q.OriginalAccess)))
813 break;
814 }
815
816 // Cache everything else on the way back. The caller should cache
817 // Q.OriginalAccess for us.
818 for (; N != 0; --N) {
819 MemoryAccess *CacheAccess = DFI.getPath(N - 1);
820 doCacheInsert(CacheAccess, ModifyingAccess, Q, Loc);
821 }
822 assert(Q.Visited.size() < 1000 && "Visited too much");
823
824 return {ModifyingAccess, Loc};
825}
826
827/// \brief Walk the use-def chains starting at \p MA and find
828/// the MemoryAccess that actually clobbers Loc.
829///
830/// \returns our clobbering memory access
831MemoryAccess *
832CachingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *StartingAccess,
833 UpwardsMemoryQuery &Q) {
834 return UpwardsDFSWalk(StartingAccess, Q.StartingLoc, Q, false).first;
835}
836
837MemoryAccess *
838CachingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *StartingAccess,
839 MemoryLocation &Loc) {
840 if (isa<MemoryPhi>(StartingAccess))
841 return StartingAccess;
842
843 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
844 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
845 return StartingUseOrDef;
846
847 Instruction *I = StartingUseOrDef->getMemoryInst();
848
849 // Conservatively, fences are always clobbers, so don't perform the walk if we
850 // hit a fence.
851 if (isa<FenceInst>(I))
852 return StartingUseOrDef;
853
854 UpwardsMemoryQuery Q;
855 Q.OriginalAccess = StartingUseOrDef;
856 Q.StartingLoc = Loc;
857 Q.Inst = StartingUseOrDef->getMemoryInst();
858 Q.IsCall = false;
859 Q.DL = &Q.Inst->getModule()->getDataLayout();
860
861 if (auto CacheResult = doCacheLookup(StartingUseOrDef, Q, Q.StartingLoc))
862 return CacheResult;
863
864 // Unlike the other function, do not walk to the def of a def, because we are
865 // handed something we already believe is the clobbering access.
866 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
867 ? StartingUseOrDef->getDefiningAccess()
868 : StartingUseOrDef;
869
870 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
871 doCacheInsert(Q.OriginalAccess, Clobber, Q, Q.StartingLoc);
872 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
873 DEBUG(dbgs() << *StartingUseOrDef << "\n");
874 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
875 DEBUG(dbgs() << *Clobber << "\n");
876 return Clobber;
877}
878
879MemoryAccess *
880CachingMemorySSAWalker::getClobberingMemoryAccess(const Instruction *I) {
881 // There should be no way to lookup an instruction and get a phi as the
882 // access, since we only map BB's to PHI's. So, this must be a use or def.
883 auto *StartingAccess = cast<MemoryUseOrDef>(MSSA->getMemoryAccess(I));
884
885 // We can't sanely do anything with a FenceInst, they conservatively
886 // clobber all memory, and have no locations to get pointers from to
887 // try to disambiguate
888 if (isa<FenceInst>(I))
889 return StartingAccess;
890
891 UpwardsMemoryQuery Q;
892 Q.OriginalAccess = StartingAccess;
893 Q.IsCall = bool(ImmutableCallSite(I));
894 if (!Q.IsCall)
895 Q.StartingLoc = MemoryLocation::get(I);
896 Q.Inst = I;
897 Q.DL = &Q.Inst->getModule()->getDataLayout();
898 if (auto CacheResult = doCacheLookup(StartingAccess, Q, Q.StartingLoc))
899 return CacheResult;
900
901 // Start with the thing we already think clobbers this location
902 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
903
904 // At this point, DefiningAccess may be the live on entry def.
905 // If it is, we will not get a better result.
906 if (MSSA->isLiveOnEntryDef(DefiningAccess))
907 return DefiningAccess;
908
909 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
910 doCacheInsert(Q.OriginalAccess, Result, Q, Q.StartingLoc);
911 // TODO: When this implementation is more mature, we may want to figure out
912 // what this additional caching buys us. It's most likely A Good Thing.
913 if (Q.IsCall)
914 for (const MemoryAccess *MA : Q.VisitedCalls)
915 doCacheInsert(MA, Result, Q, Q.StartingLoc);
916
917 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
918 DEBUG(dbgs() << *DefiningAccess << "\n");
919 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
920 DEBUG(dbgs() << *Result << "\n");
921
922 return Result;
923}
924
925MemoryAccess *
926DoNothingMemorySSAWalker::getClobberingMemoryAccess(const Instruction *I) {
927 MemoryAccess *MA = MSSA->getMemoryAccess(I);
928 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
929 return Use->getDefiningAccess();
930 return MA;
931}
932
933MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
934 MemoryAccess *StartingAccess, MemoryLocation &) {
935 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
936 return Use->getDefiningAccess();
937 return StartingAccess;
938}
939}