blob: 54133f0df93c2c87c8a17e2b24a0ad166bc5b710 [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;
Daniel Berlin1b51a292016-02-07 01:52:19 +0000252 SmallPtrSet<BasicBlock *, 32> DefUseBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +0000253 // Go through each block, figure out where defs occur, and chain together all
254 // the accesses.
255 for (BasicBlock &B : F) {
Daniel Berlin1b51a292016-02-07 01:52:19 +0000256 bool InsertIntoDefUse = false;
Daniel Berlin7898ca62016-02-07 01:52:15 +0000257 bool InsertIntoDef = false;
George Burgess IVe1100f52016-02-02 22:46:49 +0000258 AccessListType *Accesses = nullptr;
259 for (Instruction &I : B) {
260 MemoryAccess *MA = createNewAccess(&I, true);
261 if (!MA)
262 continue;
263 if (isa<MemoryDef>(MA))
Daniel Berlin7898ca62016-02-07 01:52:15 +0000264 InsertIntoDef = true;
Daniel Berlin1b51a292016-02-07 01:52:19 +0000265 else if (isa<MemoryUse>(MA))
266 InsertIntoDefUse = true;
267
George Burgess IVe1100f52016-02-02 22:46:49 +0000268 if (!Accesses)
269 Accesses = getOrCreateAccessList(&B);
270 Accesses->push_back(MA);
271 }
Daniel Berlin7898ca62016-02-07 01:52:15 +0000272 if (InsertIntoDef)
273 DefiningBlocks.insert(&B);
Daniel Berlin1b51a292016-02-07 01:52:19 +0000274 if (InsertIntoDefUse)
275 DefUseBlocks.insert(&B);
276 }
277
278 // Compute live-in.
279 // Live in is normally defined as "all the blocks on the path from each def to
280 // each of it's uses".
281 // MemoryDef's are implicit uses of previous state, so they are also uses.
282 // This means we don't really have def-only instructions. The only
283 // MemoryDef's that are not really uses are those that are of the LiveOnEntry
284 // variable (because LiveOnEntry can reach anywhere, and every def is a
285 // must-kill of LiveOnEntry).
286 // In theory, you could precisely compute live-in by using alias-analysis to
287 // disambiguate defs and uses to see which really pair up with which.
288 // In practice, this would be really expensive and difficult. So we simply
289 // assume all defs are also uses that need to be kept live.
290 // Because of this, the end result of this live-in computation will be "the
291 // entire set of basic blocks that reach any use".
292
293 SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
294 SmallVector<BasicBlock *, 64> LiveInBlockWorklist(DefUseBlocks.begin(),
295 DefUseBlocks.end());
296 // Now that we have a set of blocks where a value is live-in, recursively add
297 // predecessors until we find the full region the value is live.
298 while (!LiveInBlockWorklist.empty()) {
299 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
300
301 // The block really is live in here, insert it into the set. If already in
302 // the set, then it has already been processed.
303 if (!LiveInBlocks.insert(BB).second)
304 continue;
305
306 // Since the value is live into BB, it is either defined in a predecessor or
307 // live into it to.
308 LiveInBlockWorklist.append(pred_begin(BB), pred_end(BB));
George Burgess IVe1100f52016-02-02 22:46:49 +0000309 }
310
311 // Determine where our MemoryPhi's should go
312 IDFCalculator IDFs(*DT);
313 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin1b51a292016-02-07 01:52:19 +0000314 IDFs.setLiveInBlocks(LiveInBlocks);
George Burgess IVe1100f52016-02-02 22:46:49 +0000315 SmallVector<BasicBlock *, 32> IDFBlocks;
316 IDFs.calculate(IDFBlocks);
317
318 // Now place MemoryPhi nodes.
319 for (auto &BB : IDFBlocks) {
320 // Insert phi node
321 AccessListType *Accesses = getOrCreateAccessList(BB);
322 MemoryPhi *Phi = new MemoryPhi(F.getContext(), BB, NextID++);
323 InstructionToMemoryAccess.insert(std::make_pair(BB, Phi));
324 // Phi's always are placed at the front of the block.
325 Accesses->push_front(Phi);
326 }
327
328 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
329 // filled in with all blocks.
330 SmallPtrSet<BasicBlock *, 16> Visited;
331 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
332
333 // Now optimize the MemoryUse's defining access to point to the nearest
334 // dominating clobbering def.
335 // This ensures that MemoryUse's that are killed by the same store are
336 // immediate users of that store, one of the invariants we guarantee.
337 for (auto DomNode : depth_first(DT)) {
338 BasicBlock *BB = DomNode->getBlock();
339 auto AI = PerBlockAccesses.find(BB);
340 if (AI == PerBlockAccesses.end())
341 continue;
342 AccessListType *Accesses = AI->second.get();
343 for (auto &MA : *Accesses) {
344 if (auto *MU = dyn_cast<MemoryUse>(&MA)) {
345 Instruction *Inst = MU->getMemoryInst();
346 MU->setDefiningAccess(Result->getClobberingMemoryAccess(Inst));
347 }
348 }
349 }
350
351 // Mark the uses in unreachable blocks as live on entry, so that they go
352 // somewhere.
353 for (auto &BB : F)
354 if (!Visited.count(&BB))
355 markUnreachableAsLiveOnEntry(&BB);
356
357 Walker = Result;
358 return Walker;
359}
360
361/// \brief Helper function to create new memory accesses
362MemoryAccess *MemorySSA::createNewAccess(Instruction *I, bool IgnoreNonMemory) {
363 // Find out what affect this instruction has on memory.
364 ModRefInfo ModRef = AA->getModRefInfo(I);
365 bool Def = bool(ModRef & MRI_Mod);
366 bool Use = bool(ModRef & MRI_Ref);
367
368 // It's possible for an instruction to not modify memory at all. During
369 // construction, we ignore them.
370 if (IgnoreNonMemory && !Def && !Use)
371 return nullptr;
372
373 assert((Def || Use) &&
374 "Trying to create a memory access with a non-memory instruction");
375
376 MemoryUseOrDef *MA;
377 if (Def)
Daniel Berlin905a6462016-02-07 02:03:39 +0000378 MA = new MemoryDef(I->getContext(), nullptr, I, I->getParent(),
George Burgess IVe1100f52016-02-02 22:46:49 +0000379 NextID++);
380 else
381 MA =
Daniel Berlin905a6462016-02-07 02:03:39 +0000382 new MemoryUse(I->getContext(), nullptr, I, I->getParent());
George Burgess IVe1100f52016-02-02 22:46:49 +0000383 InstructionToMemoryAccess.insert(std::make_pair(I, MA));
384 return MA;
385}
386
387MemoryAccess *MemorySSA::findDominatingDef(BasicBlock *UseBlock,
388 enum InsertionPlace Where) {
389 // Handle the initial case
390 if (Where == Beginning)
391 // The only thing that could define us at the beginning is a phi node
392 if (MemoryPhi *Phi = getMemoryAccess(UseBlock))
393 return Phi;
394
395 DomTreeNode *CurrNode = DT->getNode(UseBlock);
396 // Need to be defined by our dominator
397 if (Where == Beginning)
398 CurrNode = CurrNode->getIDom();
399 Where = End;
400 while (CurrNode) {
401 auto It = PerBlockAccesses.find(CurrNode->getBlock());
402 if (It != PerBlockAccesses.end()) {
403 auto &Accesses = It->second;
404 for (auto RAI = Accesses->rbegin(), RAE = Accesses->rend(); RAI != RAE;
405 ++RAI) {
406 if (isa<MemoryDef>(*RAI) || isa<MemoryPhi>(*RAI))
407 return &*RAI;
408 }
409 }
410 CurrNode = CurrNode->getIDom();
411 }
412 return LiveOnEntryDef.get();
413}
414
415/// \brief Returns true if \p Replacer dominates \p Replacee .
416bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
417 const MemoryAccess *Replacee) const {
418 if (isa<MemoryUseOrDef>(Replacee))
419 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
420 const auto *MP = cast<MemoryPhi>(Replacee);
421 // For a phi node, the use occurs in the predecessor block of the phi node.
422 // Since we may occur multiple times in the phi node, we have to check each
423 // operand to ensure Replacer dominates each operand where Replacee occurs.
424 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +0000425 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +0000426 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
427 return false;
428 }
429 return true;
430}
431
432void MemorySSA::print(raw_ostream &OS) const {
433 MemorySSAAnnotatedWriter Writer(this);
434 F.print(OS, &Writer);
435}
436
437void MemorySSA::dump() const {
438 MemorySSAAnnotatedWriter Writer(this);
439 F.print(dbgs(), &Writer);
440}
441
442/// \brief Verify the domination properties of MemorySSA by checking that each
443/// definition dominates all of its uses.
444void MemorySSA::verifyDomination(Function &F) {
445 for (BasicBlock &B : F) {
446 // Phi nodes are attached to basic blocks
447 if (MemoryPhi *MP = getMemoryAccess(&B)) {
448 for (User *U : MP->users()) {
449 BasicBlock *UseBlock;
450 // Phi operands are used on edges, we simulate the right domination by
451 // acting as if the use occurred at the end of the predecessor block.
452 if (MemoryPhi *P = dyn_cast<MemoryPhi>(U)) {
453 for (const auto &Arg : P->operands()) {
454 if (Arg == MP) {
455 UseBlock = P->getIncomingBlock(Arg);
456 break;
457 }
458 }
459 } else {
460 UseBlock = cast<MemoryAccess>(U)->getBlock();
461 }
George Burgess IV60adac42016-02-02 23:26:01 +0000462 (void)UseBlock;
George Burgess IVe1100f52016-02-02 22:46:49 +0000463 assert(DT->dominates(MP->getBlock(), UseBlock) &&
464 "Memory PHI does not dominate it's uses");
465 }
466 }
467
468 for (Instruction &I : B) {
469 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
470 if (!MD)
471 continue;
472
473 for (const auto &U : MD->users()) {
474 BasicBlock *UseBlock;
475 // Things are allowed to flow to phi nodes over their predecessor edge.
476 if (auto *P = dyn_cast<MemoryPhi>(U)) {
477 for (const auto &Arg : P->operands()) {
478 if (Arg == MD) {
479 UseBlock = P->getIncomingBlock(Arg);
480 break;
481 }
482 }
483 } else {
484 UseBlock = cast<MemoryAccess>(U)->getBlock();
485 }
486 assert(DT->dominates(MD->getBlock(), UseBlock) &&
487 "Memory Def does not dominate it's uses");
488 }
489 }
490 }
491}
492
493/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
494/// appears in the use list of \p Def.
495///
496/// llvm_unreachable is used instead of asserts because this may be called in
497/// a build without asserts. In that case, we don't want this to turn into a
498/// nop.
499void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) {
500 // The live on entry use may cause us to get a NULL def here
501 if (!Def) {
502 if (!isLiveOnEntryDef(Use))
503 llvm_unreachable("Null def but use not point to live on entry def");
504 } else if (std::find(Def->user_begin(), Def->user_end(), Use) ==
505 Def->user_end()) {
506 llvm_unreachable("Did not find use in def's use list");
507 }
508}
509
510/// \brief Verify the immediate use information, by walking all the memory
511/// accesses and verifying that, for each use, it appears in the
512/// appropriate def's use list
513void MemorySSA::verifyDefUses(Function &F) {
514 for (BasicBlock &B : F) {
515 // Phi nodes are attached to basic blocks
516 if (MemoryPhi *Phi = getMemoryAccess(&B))
517 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
518 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
519
520 for (Instruction &I : B) {
521 if (MemoryAccess *MA = getMemoryAccess(&I)) {
522 assert(isa<MemoryUseOrDef>(MA) &&
523 "Found a phi node not attached to a bb");
524 verifyUseInDefs(cast<MemoryUseOrDef>(MA)->getDefiningAccess(), MA);
525 }
526 }
527 }
528}
529
530MemoryAccess *MemorySSA::getMemoryAccess(const Value *I) const {
531 return InstructionToMemoryAccess.lookup(I);
532}
533
534MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
535 return cast_or_null<MemoryPhi>(getMemoryAccess((const Value *)BB));
536}
537
538/// \brief Determine, for two memory accesses in the same block,
539/// whether \p Dominator dominates \p Dominatee.
540/// \returns True if \p Dominator dominates \p Dominatee.
541bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
542 const MemoryAccess *Dominatee) const {
543
544 assert((Dominator->getBlock() == Dominatee->getBlock()) &&
545 "Asking for local domination when accesses are in different blocks!");
546 // Get the access list for the block
547 const AccessListType *AccessList = getBlockAccesses(Dominator->getBlock());
548 AccessListType::const_reverse_iterator It(Dominator->getIterator());
549
550 // If we hit the beginning of the access list before we hit dominatee, we must
551 // dominate it
552 return std::none_of(It, AccessList->rend(),
553 [&](const MemoryAccess &MA) { return &MA == Dominatee; });
554}
555
556const static char LiveOnEntryStr[] = "liveOnEntry";
557
558void MemoryDef::print(raw_ostream &OS) const {
559 MemoryAccess *UO = getDefiningAccess();
560
561 OS << getID() << " = MemoryDef(";
562 if (UO && UO->getID())
563 OS << UO->getID();
564 else
565 OS << LiveOnEntryStr;
566 OS << ')';
567}
568
569void MemoryPhi::print(raw_ostream &OS) const {
570 bool First = true;
571 OS << getID() << " = MemoryPhi(";
572 for (const auto &Op : operands()) {
573 BasicBlock *BB = getIncomingBlock(Op);
574 MemoryAccess *MA = cast<MemoryAccess>(Op);
575 if (!First)
576 OS << ',';
577 else
578 First = false;
579
580 OS << '{';
581 if (BB->hasName())
582 OS << BB->getName();
583 else
584 BB->printAsOperand(OS, false);
585 OS << ',';
586 if (unsigned ID = MA->getID())
587 OS << ID;
588 else
589 OS << LiveOnEntryStr;
590 OS << '}';
591 }
592 OS << ')';
593}
594
595MemoryAccess::~MemoryAccess() {}
596
597void MemoryUse::print(raw_ostream &OS) const {
598 MemoryAccess *UO = getDefiningAccess();
599 OS << "MemoryUse(";
600 if (UO && UO->getID())
601 OS << UO->getID();
602 else
603 OS << LiveOnEntryStr;
604 OS << ')';
605}
606
607void MemoryAccess::dump() const {
608 print(dbgs());
609 dbgs() << "\n";
610}
611
612char MemorySSAPrinterPass::ID = 0;
613
614MemorySSAPrinterPass::MemorySSAPrinterPass() : FunctionPass(ID) {
615 initializeMemorySSAPrinterPassPass(*PassRegistry::getPassRegistry());
616}
617
618void MemorySSAPrinterPass::releaseMemory() {
619 // Subtlety: Be sure to delete the walker before MSSA, because the walker's
620 // dtor may try to access MemorySSA.
621 Walker.reset();
622 MSSA.reset();
623}
624
625void MemorySSAPrinterPass::getAnalysisUsage(AnalysisUsage &AU) const {
626 AU.setPreservesAll();
627 AU.addRequired<AAResultsWrapperPass>();
628 AU.addRequired<DominatorTreeWrapperPass>();
629 AU.addPreserved<DominatorTreeWrapperPass>();
630 AU.addPreserved<GlobalsAAWrapperPass>();
631}
632
633bool MemorySSAPrinterPass::doInitialization(Module &M) {
George Burgess IV60adac42016-02-02 23:26:01 +0000634 VerifyMemorySSA = M.getContext()
635 .getOption<bool, MemorySSAPrinterPass,
636 &MemorySSAPrinterPass::VerifyMemorySSA>();
George Burgess IVe1100f52016-02-02 22:46:49 +0000637 return false;
638}
639
640void MemorySSAPrinterPass::registerOptions() {
641 OptionRegistry::registerOption<bool, MemorySSAPrinterPass,
642 &MemorySSAPrinterPass::VerifyMemorySSA>(
643 "verify-memoryssa", "Run the Memory SSA verifier", false);
644}
645
646void MemorySSAPrinterPass::print(raw_ostream &OS, const Module *M) const {
647 MSSA->print(OS);
648}
649
650bool MemorySSAPrinterPass::runOnFunction(Function &F) {
651 this->F = &F;
652 MSSA.reset(new MemorySSA(F));
653 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
654 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
655 Walker.reset(MSSA->buildMemorySSA(AA, DT));
656
657 if (VerifyMemorySSA) {
658 MSSA->verifyDefUses(F);
659 MSSA->verifyDomination(F);
660 }
661
662 return false;
663}
664
665char MemorySSALazy::ID = 0;
666
667MemorySSALazy::MemorySSALazy() : FunctionPass(ID) {
668 initializeMemorySSALazyPass(*PassRegistry::getPassRegistry());
669}
670
671void MemorySSALazy::releaseMemory() { MSSA.reset(); }
672
673bool MemorySSALazy::runOnFunction(Function &F) {
674 MSSA.reset(new MemorySSA(F));
675 return false;
676}
677
678MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
679
680CachingMemorySSAWalker::CachingMemorySSAWalker(MemorySSA *M, AliasAnalysis *A,
681 DominatorTree *D)
682 : MemorySSAWalker(M), AA(A), DT(D) {}
683
684CachingMemorySSAWalker::~CachingMemorySSAWalker() {}
685
686struct CachingMemorySSAWalker::UpwardsMemoryQuery {
687 // True if we saw a phi whose predecessor was a backedge
688 bool SawBackedgePhi;
689 // True if our original query started off as a call
690 bool IsCall;
691 // The pointer location we started the query with. This will be empty if
692 // IsCall is true.
693 MemoryLocation StartingLoc;
694 // This is the instruction we were querying about.
695 const Instruction *Inst;
696 // Set of visited Instructions for this query.
697 DenseSet<MemoryAccessPair> Visited;
698 // Set of visited call accesses for this query. This is separated out because
699 // you can always cache and lookup the result of call queries (IE when IsCall
700 // == true) for every call in the chain. The calls have no AA location
701 // associated with them with them, and thus, no context dependence.
702 SmallPtrSet<const MemoryAccess *, 32> VisitedCalls;
703 // The MemoryAccess we actually got called with, used to test local domination
704 const MemoryAccess *OriginalAccess;
705 // The Datalayout for the module we started in
706 const DataLayout *DL;
707
708 UpwardsMemoryQuery()
709 : SawBackedgePhi(false), IsCall(false), Inst(nullptr),
710 OriginalAccess(nullptr), DL(nullptr) {}
711};
712
713void CachingMemorySSAWalker::doCacheRemove(const MemoryAccess *M,
714 const UpwardsMemoryQuery &Q,
715 const MemoryLocation &Loc) {
716 if (Q.IsCall)
717 CachedUpwardsClobberingCall.erase(M);
718 else
719 CachedUpwardsClobberingAccess.erase({M, Loc});
720}
721
722void CachingMemorySSAWalker::doCacheInsert(const MemoryAccess *M,
723 MemoryAccess *Result,
724 const UpwardsMemoryQuery &Q,
725 const MemoryLocation &Loc) {
726 ++NumClobberCacheInserts;
727 if (Q.IsCall)
728 CachedUpwardsClobberingCall[M] = Result;
729 else
730 CachedUpwardsClobberingAccess[{M, Loc}] = Result;
731}
732
733MemoryAccess *CachingMemorySSAWalker::doCacheLookup(const MemoryAccess *M,
734 const UpwardsMemoryQuery &Q,
735 const MemoryLocation &Loc) {
736 ++NumClobberCacheLookups;
737 MemoryAccess *Result = nullptr;
738
739 if (Q.IsCall)
740 Result = CachedUpwardsClobberingCall.lookup(M);
741 else
742 Result = CachedUpwardsClobberingAccess.lookup({M, Loc});
743
744 if (Result)
745 ++NumClobberCacheHits;
746 return Result;
747}
748
749bool CachingMemorySSAWalker::instructionClobbersQuery(
750 const MemoryDef *MD, UpwardsMemoryQuery &Q,
751 const MemoryLocation &Loc) const {
752 Instruction *DefMemoryInst = MD->getMemoryInst();
753 assert(DefMemoryInst && "Defining instruction not actually an instruction");
754
755 if (!Q.IsCall)
756 return AA->getModRefInfo(DefMemoryInst, Loc) & MRI_Mod;
757
758 // If this is a call, mark it for caching
759 if (ImmutableCallSite(DefMemoryInst))
760 Q.VisitedCalls.insert(MD);
761 ModRefInfo I = AA->getModRefInfo(DefMemoryInst, ImmutableCallSite(Q.Inst));
762 return I != MRI_NoModRef;
763}
764
765MemoryAccessPair CachingMemorySSAWalker::UpwardsDFSWalk(
766 MemoryAccess *StartingAccess, const MemoryLocation &Loc,
767 UpwardsMemoryQuery &Q, bool FollowingBackedge) {
768 MemoryAccess *ModifyingAccess = nullptr;
769
770 auto DFI = df_begin(StartingAccess);
771 for (auto DFE = df_end(StartingAccess); DFI != DFE;) {
772 MemoryAccess *CurrAccess = *DFI;
773 if (MSSA->isLiveOnEntryDef(CurrAccess))
774 return {CurrAccess, Loc};
775 if (auto CacheResult = doCacheLookup(CurrAccess, Q, Loc))
776 return {CacheResult, Loc};
777 // If this is a MemoryDef, check whether it clobbers our current query.
778 if (auto *MD = dyn_cast<MemoryDef>(CurrAccess)) {
779 // If we hit the top, stop following this path.
780 // While we can do lookups, we can't sanely do inserts here unless we were
781 // to track everything we saw along the way, since we don't know where we
782 // will stop.
783 if (instructionClobbersQuery(MD, Q, Loc)) {
784 ModifyingAccess = CurrAccess;
785 break;
786 }
787 }
788
789 // We need to know whether it is a phi so we can track backedges.
790 // Otherwise, walk all upward defs.
791 if (!isa<MemoryPhi>(CurrAccess)) {
792 ++DFI;
793 continue;
794 }
795
796 // Recurse on PHI nodes, since we need to change locations.
797 // TODO: Allow graphtraits on pairs, which would turn this whole function
798 // into a normal single depth first walk.
799 MemoryAccess *FirstDef = nullptr;
800 DFI = DFI.skipChildren();
801 const MemoryAccessPair PHIPair(CurrAccess, Loc);
802 bool VisitedOnlyOne = true;
803 for (auto MPI = upward_defs_begin(PHIPair), MPE = upward_defs_end();
804 MPI != MPE; ++MPI) {
805 // Don't follow this path again if we've followed it once
806 if (!Q.Visited.insert(*MPI).second)
807 continue;
808
809 bool Backedge =
810 !FollowingBackedge &&
811 DT->dominates(CurrAccess->getBlock(), MPI.getPhiArgBlock());
812
813 MemoryAccessPair CurrentPair =
814 UpwardsDFSWalk(MPI->first, MPI->second, Q, Backedge);
815 // All the phi arguments should reach the same point if we can bypass
816 // this phi. The alternative is that they hit this phi node, which
817 // means we can skip this argument.
818 if (FirstDef && CurrentPair.first != PHIPair.first &&
819 CurrentPair.first != FirstDef) {
820 ModifyingAccess = CurrAccess;
821 break;
822 }
823
824 if (!FirstDef)
825 FirstDef = CurrentPair.first;
826 else
827 VisitedOnlyOne = false;
828 }
829
830 // The above loop determines if all arguments of the phi node reach the
831 // same place. However we skip arguments that are cyclically dependent
832 // only on the value of this phi node. This means in some cases, we may
833 // only visit one argument of the phi node, and the above loop will
834 // happily say that all the arguments are the same. However, in that case,
835 // we still can't walk past the phi node, because that argument still
836 // kills the access unless we hit the top of the function when walking
837 // that argument.
838 if (VisitedOnlyOne && FirstDef && !MSSA->isLiveOnEntryDef(FirstDef))
839 ModifyingAccess = CurrAccess;
840 }
841
842 if (!ModifyingAccess)
843 return {MSSA->getLiveOnEntryDef(), Q.StartingLoc};
844
845 const BasicBlock *OriginalBlock = Q.OriginalAccess->getBlock();
846 unsigned N = DFI.getPathLength();
847 MemoryAccess *FinalAccess = ModifyingAccess;
848 for (; N != 0; --N) {
849 ModifyingAccess = DFI.getPath(N - 1);
850 BasicBlock *CurrBlock = ModifyingAccess->getBlock();
851 if (!FollowingBackedge)
852 doCacheInsert(ModifyingAccess, FinalAccess, Q, Loc);
853 if (DT->dominates(CurrBlock, OriginalBlock) &&
854 (CurrBlock != OriginalBlock || !FollowingBackedge ||
855 MSSA->locallyDominates(ModifyingAccess, Q.OriginalAccess)))
856 break;
857 }
858
859 // Cache everything else on the way back. The caller should cache
860 // Q.OriginalAccess for us.
861 for (; N != 0; --N) {
862 MemoryAccess *CacheAccess = DFI.getPath(N - 1);
863 doCacheInsert(CacheAccess, ModifyingAccess, Q, Loc);
864 }
865 assert(Q.Visited.size() < 1000 && "Visited too much");
866
867 return {ModifyingAccess, Loc};
868}
869
870/// \brief Walk the use-def chains starting at \p MA and find
871/// the MemoryAccess that actually clobbers Loc.
872///
873/// \returns our clobbering memory access
874MemoryAccess *
875CachingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *StartingAccess,
876 UpwardsMemoryQuery &Q) {
877 return UpwardsDFSWalk(StartingAccess, Q.StartingLoc, Q, false).first;
878}
879
880MemoryAccess *
881CachingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *StartingAccess,
882 MemoryLocation &Loc) {
883 if (isa<MemoryPhi>(StartingAccess))
884 return StartingAccess;
885
886 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
887 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
888 return StartingUseOrDef;
889
890 Instruction *I = StartingUseOrDef->getMemoryInst();
891
892 // Conservatively, fences are always clobbers, so don't perform the walk if we
893 // hit a fence.
894 if (isa<FenceInst>(I))
895 return StartingUseOrDef;
896
897 UpwardsMemoryQuery Q;
898 Q.OriginalAccess = StartingUseOrDef;
899 Q.StartingLoc = Loc;
900 Q.Inst = StartingUseOrDef->getMemoryInst();
901 Q.IsCall = false;
902 Q.DL = &Q.Inst->getModule()->getDataLayout();
903
904 if (auto CacheResult = doCacheLookup(StartingUseOrDef, Q, Q.StartingLoc))
905 return CacheResult;
906
907 // Unlike the other function, do not walk to the def of a def, because we are
908 // handed something we already believe is the clobbering access.
909 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
910 ? StartingUseOrDef->getDefiningAccess()
911 : StartingUseOrDef;
912
913 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
914 doCacheInsert(Q.OriginalAccess, Clobber, Q, Q.StartingLoc);
915 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
916 DEBUG(dbgs() << *StartingUseOrDef << "\n");
917 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
918 DEBUG(dbgs() << *Clobber << "\n");
919 return Clobber;
920}
921
922MemoryAccess *
923CachingMemorySSAWalker::getClobberingMemoryAccess(const Instruction *I) {
924 // There should be no way to lookup an instruction and get a phi as the
925 // access, since we only map BB's to PHI's. So, this must be a use or def.
926 auto *StartingAccess = cast<MemoryUseOrDef>(MSSA->getMemoryAccess(I));
927
928 // We can't sanely do anything with a FenceInst, they conservatively
929 // clobber all memory, and have no locations to get pointers from to
930 // try to disambiguate
931 if (isa<FenceInst>(I))
932 return StartingAccess;
933
934 UpwardsMemoryQuery Q;
935 Q.OriginalAccess = StartingAccess;
936 Q.IsCall = bool(ImmutableCallSite(I));
937 if (!Q.IsCall)
938 Q.StartingLoc = MemoryLocation::get(I);
939 Q.Inst = I;
940 Q.DL = &Q.Inst->getModule()->getDataLayout();
941 if (auto CacheResult = doCacheLookup(StartingAccess, Q, Q.StartingLoc))
942 return CacheResult;
943
944 // Start with the thing we already think clobbers this location
945 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
946
947 // At this point, DefiningAccess may be the live on entry def.
948 // If it is, we will not get a better result.
949 if (MSSA->isLiveOnEntryDef(DefiningAccess))
950 return DefiningAccess;
951
952 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
953 doCacheInsert(Q.OriginalAccess, Result, Q, Q.StartingLoc);
954 // TODO: When this implementation is more mature, we may want to figure out
955 // what this additional caching buys us. It's most likely A Good Thing.
956 if (Q.IsCall)
957 for (const MemoryAccess *MA : Q.VisitedCalls)
958 doCacheInsert(MA, Result, Q, Q.StartingLoc);
959
960 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
961 DEBUG(dbgs() << *DefiningAccess << "\n");
962 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
963 DEBUG(dbgs() << *Result << "\n");
964
965 return Result;
966}
967
968MemoryAccess *
969DoNothingMemorySSAWalker::getClobberingMemoryAccess(const Instruction *I) {
970 MemoryAccess *MA = MSSA->getMemoryAccess(I);
971 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
972 return Use->getDefiningAccess();
973 return MA;
974}
975
976MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
977 MemoryAccess *StartingAccess, MemoryLocation &) {
978 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
979 return Use->getDefiningAccess();
980 return StartingAccess;
981}
982}