blob: bbf8eff8b73fb279beb94d52a6fb68174f02d5f0 [file] [log] [blame]
George Burgess IVe1100f52016-02-02 22:46:49 +00001//===-- MemorySSA.cpp - Memory SSA Builder---------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------===//
9//
10// This file implements the MemorySSA class.
11//
12//===----------------------------------------------------------------===//
Daniel Berlin16ed57c2016-06-27 18:22:27 +000013#include "llvm/Transforms/Utils/MemorySSA.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000014#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/DenseSet.h"
16#include "llvm/ADT/DepthFirstIterator.h"
17#include "llvm/ADT/GraphTraits.h"
18#include "llvm/ADT/PostOrderIterator.h"
19#include "llvm/ADT/STLExtras.h"
George Burgess IV5f308972016-07-19 01:29:15 +000020#include "llvm/ADT/SmallBitVector.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000021#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/Analysis/AliasAnalysis.h"
25#include "llvm/Analysis/CFG.h"
26#include "llvm/Analysis/GlobalsModRef.h"
27#include "llvm/Analysis/IteratedDominanceFrontier.h"
28#include "llvm/Analysis/MemoryLocation.h"
29#include "llvm/Analysis/PHITransAddr.h"
30#include "llvm/IR/AssemblyAnnotationWriter.h"
31#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/Dominators.h"
33#include "llvm/IR/GlobalVariable.h"
34#include "llvm/IR/IRBuilder.h"
35#include "llvm/IR/IntrinsicInst.h"
36#include "llvm/IR/LLVMContext.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
39#include "llvm/IR/PatternMatch.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000040#include "llvm/Support/Debug.h"
41#include "llvm/Support/FormattedStream.h"
42#include "llvm/Transforms/Scalar.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000043#include <algorithm>
44
45#define DEBUG_TYPE "memoryssa"
46using namespace llvm;
Geoff Berryefb0dd12016-06-14 21:19:40 +000047INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
Geoff Berryb96d3b22016-06-01 21:30:40 +000048 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000049INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
50INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Geoff Berryefb0dd12016-06-14 21:19:40 +000051INITIALIZE_PASS_END(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
52 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000053
Chad Rosier232e29e2016-07-06 21:20:47 +000054INITIALIZE_PASS_BEGIN(MemorySSAPrinterLegacyPass, "print-memoryssa",
55 "Memory SSA Printer", false, false)
56INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
57INITIALIZE_PASS_END(MemorySSAPrinterLegacyPass, "print-memoryssa",
58 "Memory SSA Printer", false, false)
59
Daniel Berlinc43aa5a2016-08-02 16:24:03 +000060static cl::opt<unsigned> MaxCheckLimit(
61 "memssa-check-limit", cl::Hidden, cl::init(100),
62 cl::desc("The maximum number of stores/phis MemorySSA"
63 "will consider trying to walk past (default = 100)"));
64
Chad Rosier232e29e2016-07-06 21:20:47 +000065static cl::opt<bool>
66 VerifyMemorySSA("verify-memoryssa", cl::init(false), cl::Hidden,
67 cl::desc("Verify MemorySSA in legacy printer pass."));
68
George Burgess IVe1100f52016-02-02 22:46:49 +000069namespace llvm {
George Burgess IVe1100f52016-02-02 22:46:49 +000070/// \brief An assembly annotator class to print Memory SSA information in
71/// comments.
72class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
73 friend class MemorySSA;
74 const MemorySSA *MSSA;
75
76public:
77 MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
78
79 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
80 formatted_raw_ostream &OS) {
81 if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
82 OS << "; " << *MA << "\n";
83 }
84
85 virtual void emitInstructionAnnot(const Instruction *I,
86 formatted_raw_ostream &OS) {
87 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
88 OS << "; " << *MA << "\n";
89 }
90};
George Burgess IV5f308972016-07-19 01:29:15 +000091}
George Burgess IVfd1f2f82016-06-24 21:02:12 +000092
George Burgess IV5f308972016-07-19 01:29:15 +000093namespace {
Daniel Berlindff31de2016-08-02 21:57:52 +000094/// Our current alias analysis API differentiates heavily between calls and
95/// non-calls, and functions called on one usually assert on the other.
96/// This class encapsulates the distinction to simplify other code that wants
97/// "Memory affecting instructions and related data" to use as a key.
98/// For example, this class is used as a densemap key in the use optimizer.
99class MemoryLocOrCall {
100public:
101 MemoryLocOrCall() : IsCall(false) {}
102 MemoryLocOrCall(MemoryUseOrDef *MUD)
103 : MemoryLocOrCall(MUD->getMemoryInst()) {}
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000104 MemoryLocOrCall(const MemoryUseOrDef *MUD)
105 : MemoryLocOrCall(MUD->getMemoryInst()) {}
Daniel Berlindff31de2016-08-02 21:57:52 +0000106
107 MemoryLocOrCall(Instruction *Inst) {
108 if (ImmutableCallSite(Inst)) {
109 IsCall = true;
110 CS = ImmutableCallSite(Inst);
111 } else {
112 IsCall = false;
113 // There is no such thing as a memorylocation for a fence inst, and it is
114 // unique in that regard.
115 if (!isa<FenceInst>(Inst))
116 Loc = MemoryLocation::get(Inst);
117 }
118 }
119
120 explicit MemoryLocOrCall(const MemoryLocation &Loc)
121 : IsCall(false), Loc(Loc) {}
122
123 bool IsCall;
124 ImmutableCallSite getCS() const {
125 assert(IsCall);
126 return CS;
127 }
128 MemoryLocation getLoc() const {
129 assert(!IsCall);
130 return Loc;
131 }
132
133 bool operator==(const MemoryLocOrCall &Other) const {
134 if (IsCall != Other.IsCall)
135 return false;
136
137 if (IsCall)
138 return CS.getCalledValue() == Other.CS.getCalledValue();
139 return Loc == Other.Loc;
140 }
141
142private:
Daniel Berlinf5361132016-10-22 04:15:41 +0000143 union {
Daniel Berlind602e042017-01-25 20:56:19 +0000144 ImmutableCallSite CS;
145 MemoryLocation Loc;
Daniel Berlinf5361132016-10-22 04:15:41 +0000146 };
Daniel Berlindff31de2016-08-02 21:57:52 +0000147};
148}
149
150namespace llvm {
151template <> struct DenseMapInfo<MemoryLocOrCall> {
152 static inline MemoryLocOrCall getEmptyKey() {
153 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getEmptyKey());
154 }
155 static inline MemoryLocOrCall getTombstoneKey() {
156 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getTombstoneKey());
157 }
158 static unsigned getHashValue(const MemoryLocOrCall &MLOC) {
159 if (MLOC.IsCall)
160 return hash_combine(MLOC.IsCall,
161 DenseMapInfo<const Value *>::getHashValue(
162 MLOC.getCS().getCalledValue()));
163 return hash_combine(
164 MLOC.IsCall, DenseMapInfo<MemoryLocation>::getHashValue(MLOC.getLoc()));
165 }
166 static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS) {
167 return LHS == RHS;
168 }
169};
Daniel Berlindf101192016-08-03 00:01:46 +0000170
George Burgess IVf7672852016-08-03 19:59:11 +0000171enum class Reorderability { Always, IfNoAlias, Never };
George Burgess IV82e355c2016-08-03 19:39:54 +0000172
173/// This does one-way checks to see if Use could theoretically be hoisted above
174/// MayClobber. This will not check the other way around.
175///
176/// This assumes that, for the purposes of MemorySSA, Use comes directly after
177/// MayClobber, with no potentially clobbering operations in between them.
178/// (Where potentially clobbering ops are memory barriers, aliased stores, etc.)
179static Reorderability getLoadReorderability(const LoadInst *Use,
180 const LoadInst *MayClobber) {
181 bool VolatileUse = Use->isVolatile();
182 bool VolatileClobber = MayClobber->isVolatile();
183 // Volatile operations may never be reordered with other volatile operations.
184 if (VolatileUse && VolatileClobber)
185 return Reorderability::Never;
186
187 // The lang ref allows reordering of volatile and non-volatile operations.
188 // Whether an aliasing nonvolatile load and volatile load can be reordered,
189 // though, is ambiguous. Because it may not be best to exploit this ambiguity,
190 // we only allow volatile/non-volatile reordering if the volatile and
191 // non-volatile operations don't alias.
192 Reorderability Result = VolatileUse || VolatileClobber
193 ? Reorderability::IfNoAlias
194 : Reorderability::Always;
195
196 // If a load is seq_cst, it cannot be moved above other loads. If its ordering
197 // is weaker, it can be moved above other loads. We just need to be sure that
198 // MayClobber isn't an acquire load, because loads can't be moved above
199 // acquire loads.
200 //
201 // Note that this explicitly *does* allow the free reordering of monotonic (or
202 // weaker) loads of the same address.
203 bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent;
204 bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(),
205 AtomicOrdering::Acquire);
206 if (SeqCstUse || MayClobberIsAcquire)
207 return Reorderability::Never;
208 return Result;
209}
210
Sebastian Popd57d93c2016-10-12 03:08:40 +0000211static bool instructionClobbersQuery(MemoryDef *MD,
212 const MemoryLocation &UseLoc,
213 const Instruction *UseInst,
214 AliasAnalysis &AA) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000215 Instruction *DefInst = MD->getMemoryInst();
216 assert(DefInst && "Defining instruction not actually an instruction");
George Burgess IV5f308972016-07-19 01:29:15 +0000217
Daniel Berlindf101192016-08-03 00:01:46 +0000218 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
219 // These intrinsics will show up as affecting memory, but they are just
220 // markers.
221 switch (II->getIntrinsicID()) {
222 case Intrinsic::lifetime_start:
223 case Intrinsic::lifetime_end:
224 case Intrinsic::invariant_start:
225 case Intrinsic::invariant_end:
226 case Intrinsic::assume:
227 return false;
228 default:
229 break;
230 }
231 }
232
Daniel Berlindff31de2016-08-02 21:57:52 +0000233 ImmutableCallSite UseCS(UseInst);
234 if (UseCS) {
235 ModRefInfo I = AA.getModRefInfo(DefInst, UseCS);
236 return I != MRI_NoModRef;
237 }
George Burgess IV82e355c2016-08-03 19:39:54 +0000238
239 if (auto *DefLoad = dyn_cast<LoadInst>(DefInst)) {
240 if (auto *UseLoad = dyn_cast<LoadInst>(UseInst)) {
241 switch (getLoadReorderability(UseLoad, DefLoad)) {
242 case Reorderability::Always:
243 return false;
244 case Reorderability::Never:
245 return true;
246 case Reorderability::IfNoAlias:
247 return !AA.isNoAlias(UseLoc, MemoryLocation::get(DefLoad));
248 }
249 }
250 }
251
Daniel Berlindff31de2016-08-02 21:57:52 +0000252 return AA.getModRefInfo(DefInst, UseLoc) & MRI_Mod;
253}
254
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000255static bool instructionClobbersQuery(MemoryDef *MD, const MemoryUseOrDef *MU,
256 const MemoryLocOrCall &UseMLOC,
257 AliasAnalysis &AA) {
258 // FIXME: This is a temporary hack to allow a single instructionClobbersQuery
259 // to exist while MemoryLocOrCall is pushed through places.
260 if (UseMLOC.IsCall)
261 return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(),
262 AA);
263 return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(),
264 AA);
265}
266
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000267// Return true when MD may alias MU, return false otherwise.
Daniel Berlindcb004f2017-03-02 23:06:46 +0000268bool MemorySSAUtil::defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
269 AliasAnalysis &AA) {
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000270 return instructionClobbersQuery(MD, MU, MemoryLocOrCall(MU), AA);
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000271}
272}
273
274namespace {
275struct UpwardsMemoryQuery {
276 // True if our original query started off as a call
277 bool IsCall;
278 // The pointer location we started the query with. This will be empty if
279 // IsCall is true.
280 MemoryLocation StartingLoc;
281 // This is the instruction we were querying about.
282 const Instruction *Inst;
283 // The MemoryAccess we actually got called with, used to test local domination
284 const MemoryAccess *OriginalAccess;
285
286 UpwardsMemoryQuery()
287 : IsCall(false), Inst(nullptr), OriginalAccess(nullptr) {}
288
289 UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
290 : IsCall(ImmutableCallSite(Inst)), Inst(Inst), OriginalAccess(Access) {
291 if (!IsCall)
292 StartingLoc = MemoryLocation::get(Inst);
293 }
294};
295
296static bool lifetimeEndsAt(MemoryDef *MD, const MemoryLocation &Loc,
297 AliasAnalysis &AA) {
298 Instruction *Inst = MD->getMemoryInst();
299 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
300 switch (II->getIntrinsicID()) {
301 case Intrinsic::lifetime_start:
302 case Intrinsic::lifetime_end:
303 return AA.isMustAlias(MemoryLocation(II->getArgOperand(1)), Loc);
304 default:
305 return false;
306 }
307 }
308 return false;
309}
310
311static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysis &AA,
312 const Instruction *I) {
313 // If the memory can't be changed, then loads of the memory can't be
314 // clobbered.
315 //
316 // FIXME: We should handle invariant groups, as well. It's a bit harder,
317 // because we need to pay close attention to invariant group barriers.
318 return isa<LoadInst>(I) && (I->getMetadata(LLVMContext::MD_invariant_load) ||
319 AA.pointsToConstantMemory(I));
320}
321
George Burgess IV5f308972016-07-19 01:29:15 +0000322/// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
323/// inbetween `Start` and `ClobberAt` can clobbers `Start`.
324///
325/// This is meant to be as simple and self-contained as possible. Because it
326/// uses no cache, etc., it can be relatively expensive.
327///
328/// \param Start The MemoryAccess that we want to walk from.
329/// \param ClobberAt A clobber for Start.
330/// \param StartLoc The MemoryLocation for Start.
331/// \param MSSA The MemorySSA isntance that Start and ClobberAt belong to.
332/// \param Query The UpwardsMemoryQuery we used for our search.
333/// \param AA The AliasAnalysis we used for our search.
334static void LLVM_ATTRIBUTE_UNUSED
335checkClobberSanity(MemoryAccess *Start, MemoryAccess *ClobberAt,
336 const MemoryLocation &StartLoc, const MemorySSA &MSSA,
337 const UpwardsMemoryQuery &Query, AliasAnalysis &AA) {
338 assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
339
340 if (MSSA.isLiveOnEntryDef(Start)) {
341 assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
342 "liveOnEntry must clobber itself");
343 return;
344 }
345
George Burgess IV5f308972016-07-19 01:29:15 +0000346 bool FoundClobber = false;
347 DenseSet<MemoryAccessPair> VisitedPhis;
348 SmallVector<MemoryAccessPair, 8> Worklist;
349 Worklist.emplace_back(Start, StartLoc);
350 // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
351 // is found, complain.
352 while (!Worklist.empty()) {
353 MemoryAccessPair MAP = Worklist.pop_back_val();
354 // All we care about is that nothing from Start to ClobberAt clobbers Start.
355 // We learn nothing from revisiting nodes.
356 if (!VisitedPhis.insert(MAP).second)
357 continue;
358
359 for (MemoryAccess *MA : def_chain(MAP.first)) {
360 if (MA == ClobberAt) {
361 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
362 // instructionClobbersQuery isn't essentially free, so don't use `|=`,
363 // since it won't let us short-circuit.
364 //
365 // Also, note that this can't be hoisted out of the `Worklist` loop,
366 // since MD may only act as a clobber for 1 of N MemoryLocations.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000367 FoundClobber =
368 FoundClobber || MSSA.isLiveOnEntryDef(MD) ||
369 instructionClobbersQuery(MD, MAP.second, Query.Inst, AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000370 }
371 break;
372 }
373
374 // We should never hit liveOnEntry, unless it's the clobber.
375 assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
376
377 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
378 (void)MD;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000379 assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA) &&
George Burgess IV5f308972016-07-19 01:29:15 +0000380 "Found clobber before reaching ClobberAt!");
381 continue;
382 }
383
384 assert(isa<MemoryPhi>(MA));
385 Worklist.append(upward_defs_begin({MA, MAP.second}), upward_defs_end());
386 }
387 }
388
389 // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
390 // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
391 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
392 "ClobberAt never acted as a clobber");
393}
394
395/// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
396/// in one class.
397class ClobberWalker {
398 /// Save a few bytes by using unsigned instead of size_t.
399 using ListIndex = unsigned;
400
401 /// Represents a span of contiguous MemoryDefs, potentially ending in a
402 /// MemoryPhi.
403 struct DefPath {
404 MemoryLocation Loc;
405 // Note that, because we always walk in reverse, Last will always dominate
406 // First. Also note that First and Last are inclusive.
407 MemoryAccess *First;
408 MemoryAccess *Last;
George Burgess IV5f308972016-07-19 01:29:15 +0000409 Optional<ListIndex> Previous;
410
411 DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
412 Optional<ListIndex> Previous)
413 : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
414
415 DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
416 Optional<ListIndex> Previous)
417 : DefPath(Loc, Init, Init, Previous) {}
418 };
419
420 const MemorySSA &MSSA;
421 AliasAnalysis &AA;
422 DominatorTree &DT;
George Burgess IV5f308972016-07-19 01:29:15 +0000423 UpwardsMemoryQuery *Query;
George Burgess IV5f308972016-07-19 01:29:15 +0000424
425 // Phi optimization bookkeeping
426 SmallVector<DefPath, 32> Paths;
427 DenseSet<ConstMemoryAccessPair> VisitedPhis;
George Burgess IV5f308972016-07-19 01:29:15 +0000428
George Burgess IV5f308972016-07-19 01:29:15 +0000429 /// Find the nearest def or phi that `From` can legally be optimized to.
Daniel Berlind0420312017-04-01 09:01:12 +0000430 const MemoryAccess *getWalkTarget(const MemoryPhi *From) const {
George Burgess IV5f308972016-07-19 01:29:15 +0000431 assert(From->getNumOperands() && "Phi with no operands?");
432
433 BasicBlock *BB = From->getBlock();
George Burgess IV5f308972016-07-19 01:29:15 +0000434 MemoryAccess *Result = MSSA.getLiveOnEntryDef();
435 DomTreeNode *Node = DT.getNode(BB);
436 while ((Node = Node->getIDom())) {
Daniel Berlin7500c562017-04-01 08:59:45 +0000437 auto *Defs = MSSA.getBlockDefs(Node->getBlock());
438 if (Defs)
Daniel Berlind0420312017-04-01 09:01:12 +0000439 return &*Defs->rbegin();
George Burgess IV5f308972016-07-19 01:29:15 +0000440 }
George Burgess IV5f308972016-07-19 01:29:15 +0000441 return Result;
442 }
443
444 /// Result of calling walkToPhiOrClobber.
445 struct UpwardsWalkResult {
446 /// The "Result" of the walk. Either a clobber, the last thing we walked, or
447 /// both.
448 MemoryAccess *Result;
449 bool IsKnownClobber;
George Burgess IV5f308972016-07-19 01:29:15 +0000450 };
451
452 /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
453 /// This will update Desc.Last as it walks. It will (optionally) also stop at
454 /// StopAt.
455 ///
456 /// This does not test for whether StopAt is a clobber
Daniel Berlind0420312017-04-01 09:01:12 +0000457 UpwardsWalkResult
458 walkToPhiOrClobber(DefPath &Desc,
459 const MemoryAccess *StopAt = nullptr) const {
George Burgess IV5f308972016-07-19 01:29:15 +0000460 assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
461
462 for (MemoryAccess *Current : def_chain(Desc.Last)) {
463 Desc.Last = Current;
464 if (Current == StopAt)
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000465 return {Current, false};
George Burgess IV5f308972016-07-19 01:29:15 +0000466
467 if (auto *MD = dyn_cast<MemoryDef>(Current))
468 if (MSSA.isLiveOnEntryDef(MD) ||
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000469 instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA))
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000470 return {MD, true};
George Burgess IV5f308972016-07-19 01:29:15 +0000471 }
472
473 assert(isa<MemoryPhi>(Desc.Last) &&
474 "Ended at a non-clobber that's not a phi?");
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000475 return {Desc.Last, false};
George Burgess IV5f308972016-07-19 01:29:15 +0000476 }
477
478 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
479 ListIndex PriorNode) {
480 auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),
481 upward_defs_end());
482 for (const MemoryAccessPair &P : UpwardDefs) {
483 PausedSearches.push_back(Paths.size());
484 Paths.emplace_back(P.second, P.first, PriorNode);
485 }
486 }
487
488 /// Represents a search that terminated after finding a clobber. This clobber
489 /// may or may not be present in the path of defs from LastNode..SearchStart,
490 /// since it may have been retrieved from cache.
491 struct TerminatedPath {
492 MemoryAccess *Clobber;
493 ListIndex LastNode;
494 };
495
496 /// Get an access that keeps us from optimizing to the given phi.
497 ///
498 /// PausedSearches is an array of indices into the Paths array. Its incoming
499 /// value is the indices of searches that stopped at the last phi optimization
500 /// target. It's left in an unspecified state.
501 ///
502 /// If this returns None, NewPaused is a vector of searches that terminated
503 /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
George Burgess IV14633b52016-08-03 01:22:19 +0000504 Optional<TerminatedPath>
Daniel Berlind0420312017-04-01 09:01:12 +0000505 getBlockingAccess(const MemoryAccess *StopWhere,
George Burgess IV5f308972016-07-19 01:29:15 +0000506 SmallVectorImpl<ListIndex> &PausedSearches,
507 SmallVectorImpl<ListIndex> &NewPaused,
508 SmallVectorImpl<TerminatedPath> &Terminated) {
509 assert(!PausedSearches.empty() && "No searches to continue?");
510
511 // BFS vs DFS really doesn't make a difference here, so just do a DFS with
512 // PausedSearches as our stack.
513 while (!PausedSearches.empty()) {
514 ListIndex PathIndex = PausedSearches.pop_back_val();
515 DefPath &Node = Paths[PathIndex];
516
517 // If we've already visited this path with this MemoryLocation, we don't
518 // need to do so again.
519 //
520 // NOTE: That we just drop these paths on the ground makes caching
521 // behavior sporadic. e.g. given a diamond:
522 // A
523 // B C
524 // D
525 //
526 // ...If we walk D, B, A, C, we'll only cache the result of phi
527 // optimization for A, B, and D; C will be skipped because it dies here.
528 // This arguably isn't the worst thing ever, since:
529 // - We generally query things in a top-down order, so if we got below D
530 // without needing cache entries for {C, MemLoc}, then chances are
531 // that those cache entries would end up ultimately unused.
532 // - We still cache things for A, so C only needs to walk up a bit.
533 // If this behavior becomes problematic, we can fix without a ton of extra
534 // work.
535 if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
536 continue;
537
538 UpwardsWalkResult Res = walkToPhiOrClobber(Node, /*StopAt=*/StopWhere);
539 if (Res.IsKnownClobber) {
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000540 assert(Res.Result != StopWhere);
George Burgess IV5f308972016-07-19 01:29:15 +0000541 // If this wasn't a cache hit, we hit a clobber when walking. That's a
542 // failure.
George Burgess IV14633b52016-08-03 01:22:19 +0000543 TerminatedPath Term{Res.Result, PathIndex};
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000544 if (!MSSA.dominates(Res.Result, StopWhere))
George Burgess IV14633b52016-08-03 01:22:19 +0000545 return Term;
George Burgess IV5f308972016-07-19 01:29:15 +0000546
547 // Otherwise, it's a valid thing to potentially optimize to.
George Burgess IV14633b52016-08-03 01:22:19 +0000548 Terminated.push_back(Term);
George Burgess IV5f308972016-07-19 01:29:15 +0000549 continue;
550 }
551
552 if (Res.Result == StopWhere) {
553 // We've hit our target. Save this path off for if we want to continue
554 // walking.
555 NewPaused.push_back(PathIndex);
556 continue;
557 }
558
559 assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
560 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
561 }
562
563 return None;
564 }
565
566 template <typename T, typename Walker>
567 struct generic_def_path_iterator
568 : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
569 std::forward_iterator_tag, T *> {
570 generic_def_path_iterator() : W(nullptr), N(None) {}
571 generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
572
573 T &operator*() const { return curNode(); }
574
575 generic_def_path_iterator &operator++() {
576 N = curNode().Previous;
577 return *this;
578 }
579
580 bool operator==(const generic_def_path_iterator &O) const {
581 if (N.hasValue() != O.N.hasValue())
582 return false;
583 return !N.hasValue() || *N == *O.N;
584 }
585
586 private:
587 T &curNode() const { return W->Paths[*N]; }
588
589 Walker *W;
590 Optional<ListIndex> N;
591 };
592
593 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
594 using const_def_path_iterator =
595 generic_def_path_iterator<const DefPath, const ClobberWalker>;
596
597 iterator_range<def_path_iterator> def_path(ListIndex From) {
598 return make_range(def_path_iterator(this, From), def_path_iterator());
599 }
600
601 iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
602 return make_range(const_def_path_iterator(this, From),
603 const_def_path_iterator());
604 }
605
606 struct OptznResult {
607 /// The path that contains our result.
608 TerminatedPath PrimaryClobber;
609 /// The paths that we can legally cache back from, but that aren't
610 /// necessarily the result of the Phi optimization.
611 SmallVector<TerminatedPath, 4> OtherClobbers;
612 };
613
614 ListIndex defPathIndex(const DefPath &N) const {
615 // The assert looks nicer if we don't need to do &N
616 const DefPath *NP = &N;
617 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
618 "Out of bounds DefPath!");
619 return NP - &Paths.front();
620 }
621
622 /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
623 /// that act as legal clobbers. Note that this won't return *all* clobbers.
624 ///
625 /// Phi optimization algorithm tl;dr:
626 /// - Find the earliest def/phi, A, we can optimize to
627 /// - Find if all paths from the starting memory access ultimately reach A
628 /// - If not, optimization isn't possible.
629 /// - Otherwise, walk from A to another clobber or phi, A'.
630 /// - If A' is a def, we're done.
631 /// - If A' is a phi, try to optimize it.
632 ///
633 /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
634 /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
635 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
636 const MemoryLocation &Loc) {
637 assert(Paths.empty() && VisitedPhis.empty() &&
638 "Reset the optimization state.");
639
640 Paths.emplace_back(Loc, Start, Phi, None);
641 // Stores how many "valid" optimization nodes we had prior to calling
642 // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
643 auto PriorPathsSize = Paths.size();
644
645 SmallVector<ListIndex, 16> PausedSearches;
646 SmallVector<ListIndex, 8> NewPaused;
647 SmallVector<TerminatedPath, 4> TerminatedPaths;
648
649 addSearches(Phi, PausedSearches, 0);
650
651 // Moves the TerminatedPath with the "most dominated" Clobber to the end of
652 // Paths.
653 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
654 assert(!Paths.empty() && "Need a path to move");
George Burgess IV5f308972016-07-19 01:29:15 +0000655 auto Dom = Paths.begin();
656 for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
657 if (!MSSA.dominates(I->Clobber, Dom->Clobber))
658 Dom = I;
659 auto Last = Paths.end() - 1;
660 if (Last != Dom)
661 std::iter_swap(Last, Dom);
662 };
663
664 MemoryPhi *Current = Phi;
665 while (1) {
666 assert(!MSSA.isLiveOnEntryDef(Current) &&
667 "liveOnEntry wasn't treated as a clobber?");
668
Daniel Berlind0420312017-04-01 09:01:12 +0000669 const auto *Target = getWalkTarget(Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000670 // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
671 // optimization for the prior phi.
672 assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
673 return MSSA.dominates(P.Clobber, Target);
674 }));
675
676 // FIXME: This is broken, because the Blocker may be reported to be
677 // liveOnEntry, and we'll happily wait for that to disappear (read: never)
George Burgess IV7f414b92016-08-22 23:40:01 +0000678 // For the moment, this is fine, since we do nothing with blocker info.
George Burgess IV14633b52016-08-03 01:22:19 +0000679 if (Optional<TerminatedPath> Blocker = getBlockingAccess(
George Burgess IV5f308972016-07-19 01:29:15 +0000680 Target, PausedSearches, NewPaused, TerminatedPaths)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000681
682 // Find the node we started at. We can't search based on N->Last, since
683 // we may have gone around a loop with a different MemoryLocation.
George Burgess IV14633b52016-08-03 01:22:19 +0000684 auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
George Burgess IV5f308972016-07-19 01:29:15 +0000685 return defPathIndex(N) < PriorPathsSize;
686 });
687 assert(Iter != def_path_iterator());
688
689 DefPath &CurNode = *Iter;
690 assert(CurNode.Last == Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000691
692 // Two things:
693 // A. We can't reliably cache all of NewPaused back. Consider a case
694 // where we have two paths in NewPaused; one of which can't optimize
695 // above this phi, whereas the other can. If we cache the second path
696 // back, we'll end up with suboptimal cache entries. We can handle
697 // cases like this a bit better when we either try to find all
698 // clobbers that block phi optimization, or when our cache starts
699 // supporting unfinished searches.
700 // B. We can't reliably cache TerminatedPaths back here without doing
701 // extra checks; consider a case like:
702 // T
703 // / \
704 // D C
705 // \ /
706 // S
707 // Where T is our target, C is a node with a clobber on it, D is a
708 // diamond (with a clobber *only* on the left or right node, N), and
709 // S is our start. Say we walk to D, through the node opposite N
710 // (read: ignoring the clobber), and see a cache entry in the top
711 // node of D. That cache entry gets put into TerminatedPaths. We then
712 // walk up to C (N is later in our worklist), find the clobber, and
713 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
714 // the bottom part of D to the cached clobber, ignoring the clobber
715 // in N. Again, this problem goes away if we start tracking all
716 // blockers for a given phi optimization.
717 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
718 return {Result, {}};
719 }
720
721 // If there's nothing left to search, then all paths led to valid clobbers
722 // that we got from our cache; pick the nearest to the start, and allow
723 // the rest to be cached back.
724 if (NewPaused.empty()) {
725 MoveDominatedPathToEnd(TerminatedPaths);
726 TerminatedPath Result = TerminatedPaths.pop_back_val();
727 return {Result, std::move(TerminatedPaths)};
728 }
729
730 MemoryAccess *DefChainEnd = nullptr;
731 SmallVector<TerminatedPath, 4> Clobbers;
732 for (ListIndex Paused : NewPaused) {
733 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
734 if (WR.IsKnownClobber)
735 Clobbers.push_back({WR.Result, Paused});
736 else
737 // Micro-opt: If we hit the end of the chain, save it.
738 DefChainEnd = WR.Result;
739 }
740
741 if (!TerminatedPaths.empty()) {
742 // If we couldn't find the dominating phi/liveOnEntry in the above loop,
743 // do it now.
744 if (!DefChainEnd)
Daniel Berlind0420312017-04-01 09:01:12 +0000745 for (auto *MA : def_chain(const_cast<MemoryAccess *>(Target)))
George Burgess IV5f308972016-07-19 01:29:15 +0000746 DefChainEnd = MA;
747
748 // If any of the terminated paths don't dominate the phi we'll try to
749 // optimize, we need to figure out what they are and quit.
750 const BasicBlock *ChainBB = DefChainEnd->getBlock();
751 for (const TerminatedPath &TP : TerminatedPaths) {
752 // Because we know that DefChainEnd is as "high" as we can go, we
753 // don't need local dominance checks; BB dominance is sufficient.
754 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
755 Clobbers.push_back(TP);
756 }
757 }
758
759 // If we have clobbers in the def chain, find the one closest to Current
760 // and quit.
761 if (!Clobbers.empty()) {
762 MoveDominatedPathToEnd(Clobbers);
763 TerminatedPath Result = Clobbers.pop_back_val();
764 return {Result, std::move(Clobbers)};
765 }
766
767 assert(all_of(NewPaused,
768 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
769
770 // Because liveOnEntry is a clobber, this must be a phi.
771 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
772
773 PriorPathsSize = Paths.size();
774 PausedSearches.clear();
775 for (ListIndex I : NewPaused)
776 addSearches(DefChainPhi, PausedSearches, I);
777 NewPaused.clear();
778
779 Current = DefChainPhi;
780 }
781 }
782
George Burgess IV5f308972016-07-19 01:29:15 +0000783 void verifyOptResult(const OptznResult &R) const {
784 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
785 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
786 }));
787 }
788
789 void resetPhiOptznState() {
790 Paths.clear();
791 VisitedPhis.clear();
792 }
793
794public:
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000795 ClobberWalker(const MemorySSA &MSSA, AliasAnalysis &AA, DominatorTree &DT)
796 : MSSA(MSSA), AA(AA), DT(DT) {}
George Burgess IV5f308972016-07-19 01:29:15 +0000797
Daniel Berlin7500c562017-04-01 08:59:45 +0000798 void reset() {}
George Burgess IV5f308972016-07-19 01:29:15 +0000799
800 /// Finds the nearest clobber for the given query, optimizing phis if
801 /// possible.
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000802 MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +0000803 Query = &Q;
804
805 MemoryAccess *Current = Start;
806 // This walker pretends uses don't exist. If we're handed one, silently grab
807 // its def. (This has the nice side-effect of ensuring we never cache uses)
808 if (auto *MU = dyn_cast<MemoryUse>(Start))
809 Current = MU->getDefiningAccess();
810
811 DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
812 // Fast path for the overly-common case (no crazy phi optimization
813 // necessary)
814 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000815 MemoryAccess *Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000816 if (WalkResult.IsKnownClobber) {
George Burgess IV93ea19b2016-07-24 07:03:49 +0000817 Result = WalkResult.Result;
818 } else {
819 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
820 Current, Q.StartingLoc);
821 verifyOptResult(OptRes);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000822 resetPhiOptznState();
823 Result = OptRes.PrimaryClobber.Clobber;
George Burgess IV5f308972016-07-19 01:29:15 +0000824 }
825
George Burgess IV5f308972016-07-19 01:29:15 +0000826#ifdef EXPENSIVE_CHECKS
George Burgess IV93ea19b2016-07-24 07:03:49 +0000827 checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000828#endif
George Burgess IV93ea19b2016-07-24 07:03:49 +0000829 return Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000830 }
Geoff Berrycdf53332016-08-08 17:52:01 +0000831
832 void verify(const MemorySSA *MSSA) { assert(MSSA == &this->MSSA); }
George Burgess IV5f308972016-07-19 01:29:15 +0000833};
834
835struct RenamePassData {
836 DomTreeNode *DTN;
837 DomTreeNode::const_iterator ChildIt;
838 MemoryAccess *IncomingVal;
839
840 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
841 MemoryAccess *M)
842 : DTN(D), ChildIt(It), IncomingVal(M) {}
843 void swap(RenamePassData &RHS) {
844 std::swap(DTN, RHS.DTN);
845 std::swap(ChildIt, RHS.ChildIt);
846 std::swap(IncomingVal, RHS.IncomingVal);
847 }
848};
849} // anonymous namespace
850
851namespace llvm {
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000852/// \brief A MemorySSAWalker that does AA walks to disambiguate accesses. It no longer does caching on its own,
853/// but the name has been retained for the moment.
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000854class MemorySSA::CachingWalker final : public MemorySSAWalker {
George Burgess IV5f308972016-07-19 01:29:15 +0000855 ClobberWalker Walker;
856 bool AutoResetWalker;
857
858 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, UpwardsMemoryQuery &);
859 void verifyRemoved(MemoryAccess *);
860
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000861public:
862 CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *);
863 ~CachingWalker() override;
864
George Burgess IV400ae402016-07-20 19:51:34 +0000865 using MemorySSAWalker::getClobberingMemoryAccess;
866 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override;
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000867 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
George Burgess IV013fd732016-10-28 19:22:46 +0000868 const MemoryLocation &) override;
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000869 void invalidateInfo(MemoryAccess *) override;
870
George Burgess IV5f308972016-07-19 01:29:15 +0000871 /// Whether we call resetClobberWalker() after each time we *actually* walk to
872 /// answer a clobber query.
873 void setAutoResetWalker(bool AutoReset) { AutoResetWalker = AutoReset; }
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000874
Daniel Berlin7500c562017-04-01 08:59:45 +0000875 /// Drop the walker's persistent data structures.
George Burgess IV5f308972016-07-19 01:29:15 +0000876 void resetClobberWalker() { Walker.reset(); }
Geoff Berrycdf53332016-08-08 17:52:01 +0000877
878 void verify(const MemorySSA *MSSA) override {
879 MemorySSAWalker::verify(MSSA);
880 Walker.verify(MSSA);
881 }
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000882};
George Burgess IVe1100f52016-02-02 22:46:49 +0000883
Daniel Berlin78cbd282017-02-20 22:26:03 +0000884void MemorySSA::renameSuccessorPhis(BasicBlock *BB, MemoryAccess *IncomingVal,
885 bool RenameAllUses) {
George Burgess IVe1100f52016-02-02 22:46:49 +0000886 // Pass through values to our successors
887 for (const BasicBlock *S : successors(BB)) {
888 auto It = PerBlockAccesses.find(S);
889 // Rename the phi nodes in our successor block
890 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
891 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +0000892 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000893 auto *Phi = cast<MemoryPhi>(&Accesses->front());
Daniel Berlin78cbd282017-02-20 22:26:03 +0000894 if (RenameAllUses) {
895 int PhiIndex = Phi->getBasicBlockIndex(BB);
896 assert(PhiIndex != -1 && "Incomplete phi during partial rename");
897 Phi->setIncomingValue(PhiIndex, IncomingVal);
898 } else
899 Phi->addIncoming(IncomingVal, BB);
George Burgess IVe1100f52016-02-02 22:46:49 +0000900 }
Daniel Berlin78cbd282017-02-20 22:26:03 +0000901}
George Burgess IVe1100f52016-02-02 22:46:49 +0000902
Daniel Berlin78cbd282017-02-20 22:26:03 +0000903/// \brief Rename a single basic block into MemorySSA form.
904/// Uses the standard SSA renaming algorithm.
905/// \returns The new incoming value.
906MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB, MemoryAccess *IncomingVal,
907 bool RenameAllUses) {
908 auto It = PerBlockAccesses.find(BB);
909 // Skip most processing if the list is empty.
910 if (It != PerBlockAccesses.end()) {
911 AccessList *Accesses = It->second.get();
912 for (MemoryAccess &L : *Accesses) {
913 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) {
914 if (MUD->getDefiningAccess() == nullptr || RenameAllUses)
915 MUD->setDefiningAccess(IncomingVal);
916 if (isa<MemoryDef>(&L))
917 IncomingVal = &L;
918 } else {
919 IncomingVal = &L;
920 }
921 }
922 }
George Burgess IVe1100f52016-02-02 22:46:49 +0000923 return IncomingVal;
924}
925
926/// \brief This is the standard SSA renaming algorithm.
927///
928/// We walk the dominator tree in preorder, renaming accesses, and then filling
929/// in phi nodes in our successors.
930void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
Daniel Berlin78cbd282017-02-20 22:26:03 +0000931 SmallPtrSetImpl<BasicBlock *> &Visited,
932 bool SkipVisited, bool RenameAllUses) {
George Burgess IVe1100f52016-02-02 22:46:49 +0000933 SmallVector<RenamePassData, 32> WorkStack;
Daniel Berlin78cbd282017-02-20 22:26:03 +0000934 // Skip everything if we already renamed this block and we are skipping.
935 // Note: You can't sink this into the if, because we need it to occur
936 // regardless of whether we skip blocks or not.
937 bool AlreadyVisited = !Visited.insert(Root->getBlock()).second;
938 if (SkipVisited && AlreadyVisited)
939 return;
940
941 IncomingVal = renameBlock(Root->getBlock(), IncomingVal, RenameAllUses);
942 renameSuccessorPhis(Root->getBlock(), IncomingVal, RenameAllUses);
George Burgess IVe1100f52016-02-02 22:46:49 +0000943 WorkStack.push_back({Root, Root->begin(), IncomingVal});
George Burgess IVe1100f52016-02-02 22:46:49 +0000944
945 while (!WorkStack.empty()) {
946 DomTreeNode *Node = WorkStack.back().DTN;
947 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
948 IncomingVal = WorkStack.back().IncomingVal;
949
950 if (ChildIt == Node->end()) {
951 WorkStack.pop_back();
952 } else {
953 DomTreeNode *Child = *ChildIt;
954 ++WorkStack.back().ChildIt;
955 BasicBlock *BB = Child->getBlock();
Daniel Berlin78cbd282017-02-20 22:26:03 +0000956 // Note: You can't sink this into the if, because we need it to occur
957 // regardless of whether we skip blocks or not.
958 AlreadyVisited = !Visited.insert(BB).second;
959 if (SkipVisited && AlreadyVisited) {
960 // We already visited this during our renaming, which can happen when
961 // being asked to rename multiple blocks. Figure out the incoming val,
962 // which is the last def.
963 // Incoming value can only change if there is a block def, and in that
964 // case, it's the last block def in the list.
965 if (auto *BlockDefs = getWritableBlockDefs(BB))
966 IncomingVal = &*BlockDefs->rbegin();
967 } else
968 IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses);
969 renameSuccessorPhis(BB, IncomingVal, RenameAllUses);
George Burgess IVe1100f52016-02-02 22:46:49 +0000970 WorkStack.push_back({Child, Child->begin(), IncomingVal});
971 }
972 }
973}
974
975/// \brief Compute dominator levels, used by the phi insertion algorithm above.
976void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) {
977 for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode());
978 DFI != DFE; ++DFI)
979 DomLevels[*DFI] = DFI.getPathLength() - 1;
980}
981
George Burgess IVa362b092016-07-06 00:28:43 +0000982/// \brief This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +0000983/// unreachable blocks, and marking all other unreachable MemoryAccess's as
984/// being uses of the live on entry definition.
985void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
986 assert(!DT->isReachableFromEntry(BB) &&
987 "Reachable block found while handling unreachable blocks");
988
Daniel Berlinfc7e6512016-07-06 05:32:05 +0000989 // Make sure phi nodes in our reachable successors end up with a
990 // LiveOnEntryDef for our incoming edge, even though our block is forward
991 // unreachable. We could just disconnect these blocks from the CFG fully,
992 // but we do not right now.
993 for (const BasicBlock *S : successors(BB)) {
994 if (!DT->isReachableFromEntry(S))
995 continue;
996 auto It = PerBlockAccesses.find(S);
997 // Rename the phi nodes in our successor block
998 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
999 continue;
1000 AccessList *Accesses = It->second.get();
1001 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1002 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1003 }
1004
George Burgess IVe1100f52016-02-02 22:46:49 +00001005 auto It = PerBlockAccesses.find(BB);
1006 if (It == PerBlockAccesses.end())
1007 return;
1008
1009 auto &Accesses = It->second;
1010 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1011 auto Next = std::next(AI);
1012 // If we have a phi, just remove it. We are going to replace all
1013 // users with live on entry.
1014 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1015 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1016 else
1017 Accesses->erase(AI);
1018 AI = Next;
1019 }
1020}
1021
Geoff Berryb96d3b22016-06-01 21:30:40 +00001022MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
1023 : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
Daniel Berlincd2deac2016-10-20 20:13:45 +00001024 NextID(INVALID_MEMORYACCESS_ID) {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001025 buildMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001026}
1027
George Burgess IVe1100f52016-02-02 22:46:49 +00001028MemorySSA::~MemorySSA() {
1029 // Drop all our references
1030 for (const auto &Pair : PerBlockAccesses)
1031 for (MemoryAccess &MA : *Pair.second)
1032 MA.dropAllReferences();
1033}
1034
Daniel Berlin14300262016-06-21 18:39:20 +00001035MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001036 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1037
1038 if (Res.second)
Daniel Berlinada263d2016-06-20 20:21:33 +00001039 Res.first->second = make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001040 return Res.first->second.get();
1041}
Daniel Berlind602e042017-01-25 20:56:19 +00001042MemorySSA::DefsList *MemorySSA::getOrCreateDefsList(const BasicBlock *BB) {
1043 auto Res = PerBlockDefs.insert(std::make_pair(BB, nullptr));
1044
1045 if (Res.second)
1046 Res.first->second = make_unique<DefsList>();
1047 return Res.first->second.get();
1048}
George Burgess IVe1100f52016-02-02 22:46:49 +00001049
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001050/// This class is a batch walker of all MemoryUse's in the program, and points
1051/// their defining access at the thing that actually clobbers them. Because it
1052/// is a batch walker that touches everything, it does not operate like the
1053/// other walkers. This walker is basically performing a top-down SSA renaming
1054/// pass, where the version stack is used as the cache. This enables it to be
1055/// significantly more time and memory efficient than using the regular walker,
1056/// which is walking bottom-up.
1057class MemorySSA::OptimizeUses {
1058public:
1059 OptimizeUses(MemorySSA *MSSA, MemorySSAWalker *Walker, AliasAnalysis *AA,
1060 DominatorTree *DT)
1061 : MSSA(MSSA), Walker(Walker), AA(AA), DT(DT) {
1062 Walker = MSSA->getWalker();
1063 }
1064
1065 void optimizeUses();
1066
1067private:
1068 /// This represents where a given memorylocation is in the stack.
1069 struct MemlocStackInfo {
1070 // This essentially is keeping track of versions of the stack. Whenever
1071 // the stack changes due to pushes or pops, these versions increase.
1072 unsigned long StackEpoch;
1073 unsigned long PopEpoch;
1074 // This is the lower bound of places on the stack to check. It is equal to
1075 // the place the last stack walk ended.
1076 // Note: Correctness depends on this being initialized to 0, which densemap
1077 // does
1078 unsigned long LowerBound;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001079 const BasicBlock *LowerBoundBlock;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001080 // This is where the last walk for this memory location ended.
1081 unsigned long LastKill;
1082 bool LastKillValid;
1083 };
1084 void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1085 SmallVectorImpl<MemoryAccess *> &,
1086 DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
1087 MemorySSA *MSSA;
1088 MemorySSAWalker *Walker;
1089 AliasAnalysis *AA;
1090 DominatorTree *DT;
1091};
1092
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001093/// Optimize the uses in a given block This is basically the SSA renaming
1094/// algorithm, with one caveat: We are able to use a single stack for all
1095/// MemoryUses. This is because the set of *possible* reaching MemoryDefs is
1096/// the same for every MemoryUse. The *actual* clobbering MemoryDef is just
1097/// going to be some position in that stack of possible ones.
1098///
1099/// We track the stack positions that each MemoryLocation needs
1100/// to check, and last ended at. This is because we only want to check the
1101/// things that changed since last time. The same MemoryLocation should
1102/// get clobbered by the same store (getModRefInfo does not use invariantness or
1103/// things like this, and if they start, we can modify MemoryLocOrCall to
1104/// include relevant data)
1105void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1106 const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1107 SmallVectorImpl<MemoryAccess *> &VersionStack,
1108 DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
1109
1110 /// If no accesses, nothing to do.
1111 MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
1112 if (Accesses == nullptr)
1113 return;
1114
1115 // Pop everything that doesn't dominate the current block off the stack,
1116 // increment the PopEpoch to account for this.
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001117 while (true) {
1118 assert(
1119 !VersionStack.empty() &&
1120 "Version stack should have liveOnEntry sentinel dominating everything");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001121 BasicBlock *BackBlock = VersionStack.back()->getBlock();
1122 if (DT->dominates(BackBlock, BB))
1123 break;
1124 while (VersionStack.back()->getBlock() == BackBlock)
1125 VersionStack.pop_back();
1126 ++PopEpoch;
1127 }
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001128
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001129 for (MemoryAccess &MA : *Accesses) {
1130 auto *MU = dyn_cast<MemoryUse>(&MA);
1131 if (!MU) {
1132 VersionStack.push_back(&MA);
1133 ++StackEpoch;
1134 continue;
1135 }
1136
George Burgess IV024f3d22016-08-03 19:57:02 +00001137 if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
Daniel Berlincd2deac2016-10-20 20:13:45 +00001138 MU->setDefiningAccess(MSSA->getLiveOnEntryDef(), true);
George Burgess IV024f3d22016-08-03 19:57:02 +00001139 continue;
1140 }
1141
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001142 MemoryLocOrCall UseMLOC(MU);
1143 auto &LocInfo = LocStackInfo[UseMLOC];
Daniel Berlin26fcea92016-08-02 20:02:21 +00001144 // If the pop epoch changed, it means we've removed stuff from top of
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001145 // stack due to changing blocks. We may have to reset the lower bound or
1146 // last kill info.
1147 if (LocInfo.PopEpoch != PopEpoch) {
1148 LocInfo.PopEpoch = PopEpoch;
1149 LocInfo.StackEpoch = StackEpoch;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001150 // If the lower bound was in something that no longer dominates us, we
1151 // have to reset it.
1152 // We can't simply track stack size, because the stack may have had
1153 // pushes/pops in the meantime.
1154 // XXX: This is non-optimal, but only is slower cases with heavily
1155 // branching dominator trees. To get the optimal number of queries would
1156 // be to make lowerbound and lastkill a per-loc stack, and pop it until
1157 // the top of that stack dominates us. This does not seem worth it ATM.
1158 // A much cheaper optimization would be to always explore the deepest
1159 // branch of the dominator tree first. This will guarantee this resets on
1160 // the smallest set of blocks.
1161 if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
Daniel Berlin1e98c042016-09-26 17:22:54 +00001162 !DT->dominates(LocInfo.LowerBoundBlock, BB)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001163 // Reset the lower bound of things to check.
1164 // TODO: Some day we should be able to reset to last kill, rather than
1165 // 0.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001166 LocInfo.LowerBound = 0;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001167 LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001168 LocInfo.LastKillValid = false;
1169 }
1170 } else if (LocInfo.StackEpoch != StackEpoch) {
1171 // If all that has changed is the StackEpoch, we only have to check the
1172 // new things on the stack, because we've checked everything before. In
1173 // this case, the lower bound of things to check remains the same.
1174 LocInfo.PopEpoch = PopEpoch;
1175 LocInfo.StackEpoch = StackEpoch;
1176 }
1177 if (!LocInfo.LastKillValid) {
1178 LocInfo.LastKill = VersionStack.size() - 1;
1179 LocInfo.LastKillValid = true;
1180 }
1181
1182 // At this point, we should have corrected last kill and LowerBound to be
1183 // in bounds.
1184 assert(LocInfo.LowerBound < VersionStack.size() &&
1185 "Lower bound out of range");
1186 assert(LocInfo.LastKill < VersionStack.size() &&
1187 "Last kill info out of range");
1188 // In any case, the new upper bound is the top of the stack.
1189 unsigned long UpperBound = VersionStack.size() - 1;
1190
1191 if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
Daniel Berlin26fcea92016-08-02 20:02:21 +00001192 DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
1193 << *(MU->getMemoryInst()) << ")"
1194 << " because there are " << UpperBound - LocInfo.LowerBound
1195 << " stores to disambiguate\n");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001196 // Because we did not walk, LastKill is no longer valid, as this may
1197 // have been a kill.
1198 LocInfo.LastKillValid = false;
1199 continue;
1200 }
1201 bool FoundClobberResult = false;
1202 while (UpperBound > LocInfo.LowerBound) {
1203 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1204 // For phis, use the walker, see where we ended up, go there
1205 Instruction *UseInst = MU->getMemoryInst();
1206 MemoryAccess *Result = Walker->getClobberingMemoryAccess(UseInst);
1207 // We are guaranteed to find it or something is wrong
1208 while (VersionStack[UpperBound] != Result) {
1209 assert(UpperBound != 0);
1210 --UpperBound;
1211 }
1212 FoundClobberResult = true;
1213 break;
1214 }
1215
1216 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
Daniel Berlindf101192016-08-03 00:01:46 +00001217 // If the lifetime of the pointer ends at this instruction, it's live on
1218 // entry.
1219 if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1220 // Reset UpperBound to liveOnEntryDef's place in the stack
1221 UpperBound = 0;
1222 FoundClobberResult = true;
1223 break;
1224 }
Daniel Berlindff31de2016-08-02 21:57:52 +00001225 if (instructionClobbersQuery(MD, MU, UseMLOC, *AA)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001226 FoundClobberResult = true;
1227 break;
1228 }
1229 --UpperBound;
1230 }
1231 // At the end of this loop, UpperBound is either a clobber, or lower bound
1232 // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1233 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
Daniel Berlincd2deac2016-10-20 20:13:45 +00001234 MU->setDefiningAccess(VersionStack[UpperBound], true);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001235 // We were last killed now by where we got to
1236 LocInfo.LastKill = UpperBound;
1237 } else {
1238 // Otherwise, we checked all the new ones, and now we know we can get to
1239 // LastKill.
Daniel Berlincd2deac2016-10-20 20:13:45 +00001240 MU->setDefiningAccess(VersionStack[LocInfo.LastKill], true);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001241 }
1242 LocInfo.LowerBound = VersionStack.size() - 1;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001243 LocInfo.LowerBoundBlock = BB;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001244 }
1245}
1246
1247/// Optimize uses to point to their actual clobbering definitions.
1248void MemorySSA::OptimizeUses::optimizeUses() {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001249 SmallVector<MemoryAccess *, 16> VersionStack;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001250 DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001251 VersionStack.push_back(MSSA->getLiveOnEntryDef());
1252
1253 unsigned long StackEpoch = 1;
1254 unsigned long PopEpoch = 1;
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001255 // We perform a non-recursive top-down dominator tree walk.
Daniel Berlin7ac3d742016-08-05 22:09:14 +00001256 for (const auto *DomNode : depth_first(DT->getRootNode()))
1257 optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1258 LocStackInfo);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001259}
1260
Daniel Berlin3d512a22016-08-22 19:14:30 +00001261void MemorySSA::placePHINodes(
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001262 const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks,
1263 const DenseMap<const BasicBlock *, unsigned int> &BBNumbers) {
Daniel Berlin3d512a22016-08-22 19:14:30 +00001264 // Determine where our MemoryPhi's should go
1265 ForwardIDFCalculator IDFs(*DT);
1266 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001267 SmallVector<BasicBlock *, 32> IDFBlocks;
1268 IDFs.calculate(IDFBlocks);
1269
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001270 std::sort(IDFBlocks.begin(), IDFBlocks.end(),
1271 [&BBNumbers](const BasicBlock *A, const BasicBlock *B) {
1272 return BBNumbers.lookup(A) < BBNumbers.lookup(B);
1273 });
1274
Daniel Berlin3d512a22016-08-22 19:14:30 +00001275 // Now place MemoryPhi nodes.
Daniel Berlind602e042017-01-25 20:56:19 +00001276 for (auto &BB : IDFBlocks)
1277 createMemoryPhi(BB);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001278}
1279
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001280void MemorySSA::buildMemorySSA() {
George Burgess IVe1100f52016-02-02 22:46:49 +00001281 // We create an access to represent "live on entry", for things like
1282 // arguments or users of globals, where the memory they use is defined before
1283 // the beginning of the function. We do not actually insert it into the IR.
1284 // We do not define a live on exit for the immediate uses, and thus our
1285 // semantics do *not* imply that something with no immediate uses can simply
1286 // be removed.
1287 BasicBlock &StartingPoint = F.getEntryBlock();
1288 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
1289 &StartingPoint, NextID++);
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001290 DenseMap<const BasicBlock *, unsigned int> BBNumbers;
1291 unsigned NextBBNum = 0;
George Burgess IVe1100f52016-02-02 22:46:49 +00001292
1293 // We maintain lists of memory accesses per-block, trading memory for time. We
1294 // could just look up the memory access for every possible instruction in the
1295 // stream.
1296 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001297 SmallPtrSet<BasicBlock *, 32> DefUseBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001298 // Go through each block, figure out where defs occur, and chain together all
1299 // the accesses.
1300 for (BasicBlock &B : F) {
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001301 BBNumbers[&B] = NextBBNum++;
Daniel Berlin7898ca62016-02-07 01:52:15 +00001302 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001303 AccessList *Accesses = nullptr;
Daniel Berlind602e042017-01-25 20:56:19 +00001304 DefsList *Defs = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001305 for (Instruction &I : B) {
Peter Collingbourneffecb142016-05-26 01:19:17 +00001306 MemoryUseOrDef *MUD = createNewAccess(&I);
George Burgess IVb42b7622016-03-11 19:34:03 +00001307 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001308 continue;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001309
George Burgess IVe1100f52016-02-02 22:46:49 +00001310 if (!Accesses)
1311 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001312 Accesses->push_back(MUD);
Daniel Berlind602e042017-01-25 20:56:19 +00001313 if (isa<MemoryDef>(MUD)) {
1314 InsertIntoDef = true;
1315 if (!Defs)
1316 Defs = getOrCreateDefsList(&B);
1317 Defs->push_back(*MUD);
1318 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001319 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001320 if (InsertIntoDef)
1321 DefiningBlocks.insert(&B);
George Burgess IV3887a412016-03-21 21:25:39 +00001322 if (Accesses)
Daniel Berlin1b51a292016-02-07 01:52:19 +00001323 DefUseBlocks.insert(&B);
1324 }
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001325 placePHINodes(DefiningBlocks, BBNumbers);
George Burgess IVe1100f52016-02-02 22:46:49 +00001326
1327 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1328 // filled in with all blocks.
1329 SmallPtrSet<BasicBlock *, 16> Visited;
1330 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1331
George Burgess IV5f308972016-07-19 01:29:15 +00001332 CachingWalker *Walker = getWalkerImpl();
1333
1334 // We're doing a batch of updates; don't drop useful caches between them.
1335 Walker->setAutoResetWalker(false);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001336 OptimizeUses(this, Walker, AA, DT).optimizeUses();
George Burgess IV5f308972016-07-19 01:29:15 +00001337 Walker->setAutoResetWalker(true);
1338 Walker->resetClobberWalker();
1339
George Burgess IVe1100f52016-02-02 22:46:49 +00001340 // Mark the uses in unreachable blocks as live on entry, so that they go
1341 // somewhere.
1342 for (auto &BB : F)
1343 if (!Visited.count(&BB))
1344 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001345}
George Burgess IVe1100f52016-02-02 22:46:49 +00001346
George Burgess IV5f308972016-07-19 01:29:15 +00001347MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1348
1349MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001350 if (Walker)
1351 return Walker.get();
1352
1353 Walker = make_unique<CachingWalker>(this, AA, DT);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001354 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001355}
1356
Daniel Berlind602e042017-01-25 20:56:19 +00001357// This is a helper function used by the creation routines. It places NewAccess
1358// into the access and defs lists for a given basic block, at the given
1359// insertion point.
1360void MemorySSA::insertIntoListsForBlock(MemoryAccess *NewAccess,
1361 const BasicBlock *BB,
1362 InsertionPlace Point) {
1363 auto *Accesses = getOrCreateAccessList(BB);
1364 if (Point == Beginning) {
1365 // If it's a phi node, it goes first, otherwise, it goes after any phi
1366 // nodes.
1367 if (isa<MemoryPhi>(NewAccess)) {
1368 Accesses->push_front(NewAccess);
1369 auto *Defs = getOrCreateDefsList(BB);
1370 Defs->push_front(*NewAccess);
1371 } else {
1372 auto AI = find_if_not(
1373 *Accesses, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1374 Accesses->insert(AI, NewAccess);
1375 if (!isa<MemoryUse>(NewAccess)) {
1376 auto *Defs = getOrCreateDefsList(BB);
1377 auto DI = find_if_not(
1378 *Defs, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1379 Defs->insert(DI, *NewAccess);
1380 }
1381 }
1382 } else {
1383 Accesses->push_back(NewAccess);
1384 if (!isa<MemoryUse>(NewAccess)) {
1385 auto *Defs = getOrCreateDefsList(BB);
1386 Defs->push_back(*NewAccess);
1387 }
1388 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001389 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001390}
1391
1392void MemorySSA::insertIntoListsBefore(MemoryAccess *What, const BasicBlock *BB,
1393 AccessList::iterator InsertPt) {
1394 auto *Accesses = getWritableBlockAccesses(BB);
1395 bool WasEnd = InsertPt == Accesses->end();
1396 Accesses->insert(AccessList::iterator(InsertPt), What);
1397 if (!isa<MemoryUse>(What)) {
1398 auto *Defs = getOrCreateDefsList(BB);
1399 // If we got asked to insert at the end, we have an easy job, just shove it
1400 // at the end. If we got asked to insert before an existing def, we also get
1401 // an terator. If we got asked to insert before a use, we have to hunt for
1402 // the next def.
1403 if (WasEnd) {
1404 Defs->push_back(*What);
1405 } else if (isa<MemoryDef>(InsertPt)) {
1406 Defs->insert(InsertPt->getDefsIterator(), *What);
1407 } else {
1408 while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt))
1409 ++InsertPt;
1410 // Either we found a def, or we are inserting at the end
1411 if (InsertPt == Accesses->end())
1412 Defs->push_back(*What);
1413 else
1414 Defs->insert(InsertPt->getDefsIterator(), *What);
1415 }
1416 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001417 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001418}
1419
Daniel Berlin60ead052017-01-28 01:23:13 +00001420// Move What before Where in the IR. The end result is taht What will belong to
1421// the right lists and have the right Block set, but will not otherwise be
1422// correct. It will not have the right defining access, and if it is a def,
1423// things below it will not properly be updated.
1424void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
1425 AccessList::iterator Where) {
1426 // Keep it in the lookup tables, remove from the lists
1427 removeFromLists(What, false);
1428 What->setBlock(BB);
1429 insertIntoListsBefore(What, BB, Where);
1430}
1431
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001432void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
1433 InsertionPlace Point) {
1434 removeFromLists(What, false);
1435 What->setBlock(BB);
1436 insertIntoListsForBlock(What, BB, Point);
1437}
1438
Daniel Berlin14300262016-06-21 18:39:20 +00001439MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1440 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
Daniel Berlin14300262016-06-21 18:39:20 +00001441 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001442 // Phi's always are placed at the front of the block.
Daniel Berlind602e042017-01-25 20:56:19 +00001443 insertIntoListsForBlock(Phi, BB, Beginning);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001444 ValueToMemoryAccess[BB] = Phi;
Daniel Berlin14300262016-06-21 18:39:20 +00001445 return Phi;
1446}
1447
1448MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
1449 MemoryAccess *Definition) {
1450 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1451 MemoryUseOrDef *NewAccess = createNewAccess(I);
1452 assert(
1453 NewAccess != nullptr &&
1454 "Tried to create a memory access for a non-memory touching instruction");
1455 NewAccess->setDefiningAccess(Definition);
1456 return NewAccess;
1457}
1458
George Burgess IVe1100f52016-02-02 22:46:49 +00001459/// \brief Helper function to create new memory accesses
Peter Collingbourneffecb142016-05-26 01:19:17 +00001460MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001461 // The assume intrinsic has a control dependency which we model by claiming
1462 // that it writes arbitrarily. Ignore that fake memory dependency here.
1463 // FIXME: Replace this special casing with a more accurate modelling of
1464 // assume's control dependency.
1465 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1466 if (II->getIntrinsicID() == Intrinsic::assume)
1467 return nullptr;
1468
George Burgess IVe1100f52016-02-02 22:46:49 +00001469 // Find out what affect this instruction has on memory.
1470 ModRefInfo ModRef = AA->getModRefInfo(I);
1471 bool Def = bool(ModRef & MRI_Mod);
1472 bool Use = bool(ModRef & MRI_Ref);
1473
1474 // It's possible for an instruction to not modify memory at all. During
1475 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +00001476 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +00001477 return nullptr;
1478
1479 assert((Def || Use) &&
1480 "Trying to create a memory access with a non-memory instruction");
1481
George Burgess IVb42b7622016-03-11 19:34:03 +00001482 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001483 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +00001484 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +00001485 else
George Burgess IVb42b7622016-03-11 19:34:03 +00001486 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
Daniel Berlin5130cc82016-07-31 21:08:20 +00001487 ValueToMemoryAccess[I] = MUD;
George Burgess IVb42b7622016-03-11 19:34:03 +00001488 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001489}
1490
George Burgess IVe1100f52016-02-02 22:46:49 +00001491/// \brief Returns true if \p Replacer dominates \p Replacee .
1492bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1493 const MemoryAccess *Replacee) const {
1494 if (isa<MemoryUseOrDef>(Replacee))
1495 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1496 const auto *MP = cast<MemoryPhi>(Replacee);
1497 // For a phi node, the use occurs in the predecessor block of the phi node.
1498 // Since we may occur multiple times in the phi node, we have to check each
1499 // operand to ensure Replacer dominates each operand where Replacee occurs.
1500 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +00001501 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +00001502 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1503 return false;
1504 }
1505 return true;
1506}
1507
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001508/// \brief Properly remove \p MA from all of MemorySSA's lookup tables.
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001509void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1510 assert(MA->use_empty() &&
1511 "Trying to remove memory access that still has uses");
Daniel Berlin5c46b942016-07-19 22:49:43 +00001512 BlockNumbering.erase(MA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001513 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
1514 MUD->setDefiningAccess(nullptr);
1515 // Invalidate our walker's cache if necessary
1516 if (!isa<MemoryUse>(MA))
1517 Walker->invalidateInfo(MA);
1518 // The call below to erase will destroy MA, so we can't change the order we
1519 // are doing things here
1520 Value *MemoryInst;
1521 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1522 MemoryInst = MUD->getMemoryInst();
1523 } else {
1524 MemoryInst = MA->getBlock();
1525 }
Daniel Berlin5130cc82016-07-31 21:08:20 +00001526 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1527 if (VMA->second == MA)
1528 ValueToMemoryAccess.erase(VMA);
Daniel Berlin60ead052017-01-28 01:23:13 +00001529}
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001530
Daniel Berlin60ead052017-01-28 01:23:13 +00001531/// \brief Properly remove \p MA from all of MemorySSA's lists.
1532///
1533/// Because of the way the intrusive list and use lists work, it is important to
1534/// do removal in the right order.
1535/// ShouldDelete defaults to true, and will cause the memory access to also be
1536/// deleted, not just removed.
1537void MemorySSA::removeFromLists(MemoryAccess *MA, bool ShouldDelete) {
Daniel Berlind602e042017-01-25 20:56:19 +00001538 // The access list owns the reference, so we erase it from the non-owning list
1539 // first.
1540 if (!isa<MemoryUse>(MA)) {
1541 auto DefsIt = PerBlockDefs.find(MA->getBlock());
1542 std::unique_ptr<DefsList> &Defs = DefsIt->second;
1543 Defs->remove(*MA);
1544 if (Defs->empty())
1545 PerBlockDefs.erase(DefsIt);
1546 }
1547
Daniel Berlin60ead052017-01-28 01:23:13 +00001548 // The erase call here will delete it. If we don't want it deleted, we call
1549 // remove instead.
George Burgess IVe0e6e482016-03-02 02:35:04 +00001550 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
Daniel Berlinada263d2016-06-20 20:21:33 +00001551 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin60ead052017-01-28 01:23:13 +00001552 if (ShouldDelete)
1553 Accesses->erase(MA);
1554 else
1555 Accesses->remove(MA);
1556
George Burgess IVe0e6e482016-03-02 02:35:04 +00001557 if (Accesses->empty())
1558 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001559}
1560
George Burgess IVe1100f52016-02-02 22:46:49 +00001561void MemorySSA::print(raw_ostream &OS) const {
1562 MemorySSAAnnotatedWriter Writer(this);
1563 F.print(OS, &Writer);
1564}
1565
Matthias Braun8c209aa2017-01-28 02:02:38 +00001566#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Daniel Berlin78cbd282017-02-20 22:26:03 +00001567LLVM_DUMP_METHOD void MemorySSA::dump() const { print(dbgs()); }
Matthias Braun8c209aa2017-01-28 02:02:38 +00001568#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001569
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001570void MemorySSA::verifyMemorySSA() const {
1571 verifyDefUses(F);
1572 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001573 verifyOrdering(F);
Geoff Berrycdf53332016-08-08 17:52:01 +00001574 Walker->verify(this);
Daniel Berlin14300262016-06-21 18:39:20 +00001575}
1576
1577/// \brief Verify that the order and existence of MemoryAccesses matches the
1578/// order and existence of memory affecting instructions.
1579void MemorySSA::verifyOrdering(Function &F) const {
1580 // Walk all the blocks, comparing what the lookups think and what the access
1581 // lists think, as well as the order in the blocks vs the order in the access
1582 // lists.
1583 SmallVector<MemoryAccess *, 32> ActualAccesses;
Daniel Berlind602e042017-01-25 20:56:19 +00001584 SmallVector<MemoryAccess *, 32> ActualDefs;
Daniel Berlin14300262016-06-21 18:39:20 +00001585 for (BasicBlock &B : F) {
1586 const AccessList *AL = getBlockAccesses(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001587 const auto *DL = getBlockDefs(&B);
Daniel Berlin14300262016-06-21 18:39:20 +00001588 MemoryAccess *Phi = getMemoryAccess(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001589 if (Phi) {
Daniel Berlin14300262016-06-21 18:39:20 +00001590 ActualAccesses.push_back(Phi);
Daniel Berlind602e042017-01-25 20:56:19 +00001591 ActualDefs.push_back(Phi);
1592 }
1593
Daniel Berlin14300262016-06-21 18:39:20 +00001594 for (Instruction &I : B) {
1595 MemoryAccess *MA = getMemoryAccess(&I);
Daniel Berlind602e042017-01-25 20:56:19 +00001596 assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) &&
1597 "We have memory affecting instructions "
1598 "in this block but they are not in the "
1599 "access list or defs list");
1600 if (MA) {
Daniel Berlin14300262016-06-21 18:39:20 +00001601 ActualAccesses.push_back(MA);
Daniel Berlind602e042017-01-25 20:56:19 +00001602 if (isa<MemoryDef>(MA))
1603 ActualDefs.push_back(MA);
1604 }
Daniel Berlin14300262016-06-21 18:39:20 +00001605 }
1606 // Either we hit the assert, really have no accesses, or we have both
Daniel Berlind602e042017-01-25 20:56:19 +00001607 // accesses and an access list.
1608 // Same with defs.
1609 if (!AL && !DL)
Daniel Berlin14300262016-06-21 18:39:20 +00001610 continue;
1611 assert(AL->size() == ActualAccesses.size() &&
1612 "We don't have the same number of accesses in the block as on the "
1613 "access list");
Davide Italiano6c77de02017-01-30 03:16:43 +00001614 assert((DL || ActualDefs.size() == 0) &&
1615 "Either we should have a defs list, or we should have no defs");
Daniel Berlind602e042017-01-25 20:56:19 +00001616 assert((!DL || DL->size() == ActualDefs.size()) &&
1617 "We don't have the same number of defs in the block as on the "
1618 "def list");
Daniel Berlin14300262016-06-21 18:39:20 +00001619 auto ALI = AL->begin();
1620 auto AAI = ActualAccesses.begin();
1621 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1622 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1623 ++ALI;
1624 ++AAI;
1625 }
1626 ActualAccesses.clear();
Daniel Berlind602e042017-01-25 20:56:19 +00001627 if (DL) {
1628 auto DLI = DL->begin();
1629 auto ADI = ActualDefs.begin();
1630 while (DLI != DL->end() && ADI != ActualDefs.end()) {
1631 assert(&*DLI == *ADI && "Not the same defs in the same order");
1632 ++DLI;
1633 ++ADI;
1634 }
1635 }
1636 ActualDefs.clear();
Daniel Berlin14300262016-06-21 18:39:20 +00001637 }
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001638}
1639
George Burgess IVe1100f52016-02-02 22:46:49 +00001640/// \brief Verify the domination properties of MemorySSA by checking that each
1641/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001642void MemorySSA::verifyDomination(Function &F) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001643#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001644 for (BasicBlock &B : F) {
1645 // Phi nodes are attached to basic blocks
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001646 if (MemoryPhi *MP = getMemoryAccess(&B))
1647 for (const Use &U : MP->uses())
1648 assert(dominates(MP, U) && "Memory PHI does not dominate it's uses");
Daniel Berlin7af95872016-08-05 21:47:20 +00001649
George Burgess IVe1100f52016-02-02 22:46:49 +00001650 for (Instruction &I : B) {
1651 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
1652 if (!MD)
1653 continue;
1654
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001655 for (const Use &U : MD->uses())
1656 assert(dominates(MD, U) && "Memory Def does not dominate it's uses");
George Burgess IVe1100f52016-02-02 22:46:49 +00001657 }
1658 }
Daniel Berlin7af95872016-08-05 21:47:20 +00001659#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001660}
1661
1662/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
1663/// appears in the use list of \p Def.
Daniel Berlin7af95872016-08-05 21:47:20 +00001664
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001665void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001666#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001667 // The live on entry use may cause us to get a NULL def here
Daniel Berlin7af95872016-08-05 21:47:20 +00001668 if (!Def)
1669 assert(isLiveOnEntryDef(Use) &&
1670 "Null def but use not point to live on entry def");
1671 else
Daniel Berlinda2f38e2016-08-11 21:26:50 +00001672 assert(is_contained(Def->users(), Use) &&
Daniel Berlin7af95872016-08-05 21:47:20 +00001673 "Did not find use in def's use list");
1674#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001675}
1676
1677/// \brief Verify the immediate use information, by walking all the memory
1678/// accesses and verifying that, for each use, it appears in the
1679/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001680void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001681 for (BasicBlock &B : F) {
1682 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00001683 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00001684 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
1685 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00001686 "Incomplete MemoryPhi Node");
George Burgess IVe1100f52016-02-02 22:46:49 +00001687 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1688 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Daniel Berlin14300262016-06-21 18:39:20 +00001689 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001690
1691 for (Instruction &I : B) {
George Burgess IV66837ab2016-11-01 21:17:46 +00001692 if (MemoryUseOrDef *MA = getMemoryAccess(&I)) {
1693 verifyUseInDefs(MA->getDefiningAccess(), MA);
George Burgess IVe1100f52016-02-02 22:46:49 +00001694 }
1695 }
1696 }
1697}
1698
George Burgess IV66837ab2016-11-01 21:17:46 +00001699MemoryUseOrDef *MemorySSA::getMemoryAccess(const Instruction *I) const {
1700 return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I));
George Burgess IVe1100f52016-02-02 22:46:49 +00001701}
1702
1703MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
George Burgess IV66837ab2016-11-01 21:17:46 +00001704 return cast_or_null<MemoryPhi>(ValueToMemoryAccess.lookup(cast<Value>(BB)));
George Burgess IVe1100f52016-02-02 22:46:49 +00001705}
1706
Daniel Berlin5c46b942016-07-19 22:49:43 +00001707/// Perform a local numbering on blocks so that instruction ordering can be
1708/// determined in constant time.
1709/// TODO: We currently just number in order. If we numbered by N, we could
1710/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
1711/// log2(N) sequences of mixed before and after) without needing to invalidate
1712/// the numbering.
1713void MemorySSA::renumberBlock(const BasicBlock *B) const {
1714 // The pre-increment ensures the numbers really start at 1.
1715 unsigned long CurrentNumber = 0;
1716 const AccessList *AL = getBlockAccesses(B);
1717 assert(AL != nullptr && "Asking to renumber an empty block");
1718 for (const auto &I : *AL)
1719 BlockNumbering[&I] = ++CurrentNumber;
1720 BlockNumberingValid.insert(B);
1721}
1722
George Burgess IVe1100f52016-02-02 22:46:49 +00001723/// \brief Determine, for two memory accesses in the same block,
1724/// whether \p Dominator dominates \p Dominatee.
1725/// \returns True if \p Dominator dominates \p Dominatee.
1726bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
1727 const MemoryAccess *Dominatee) const {
Sebastian Pope1f60b12016-06-10 21:36:41 +00001728
Daniel Berlin5c46b942016-07-19 22:49:43 +00001729 const BasicBlock *DominatorBlock = Dominator->getBlock();
Daniel Berlin5c46b942016-07-19 22:49:43 +00001730
Daniel Berlin19860302016-07-19 23:08:08 +00001731 assert((DominatorBlock == Dominatee->getBlock()) &&
Daniel Berlin5c46b942016-07-19 22:49:43 +00001732 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00001733 // A node dominates itself.
1734 if (Dominatee == Dominator)
1735 return true;
1736
1737 // When Dominatee is defined on function entry, it is not dominated by another
1738 // memory access.
1739 if (isLiveOnEntryDef(Dominatee))
1740 return false;
1741
1742 // When Dominator is defined on function entry, it dominates the other memory
1743 // access.
1744 if (isLiveOnEntryDef(Dominator))
1745 return true;
1746
Daniel Berlin5c46b942016-07-19 22:49:43 +00001747 if (!BlockNumberingValid.count(DominatorBlock))
1748 renumberBlock(DominatorBlock);
George Burgess IVe1100f52016-02-02 22:46:49 +00001749
Daniel Berlin5c46b942016-07-19 22:49:43 +00001750 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
1751 // All numbers start with 1
1752 assert(DominatorNum != 0 && "Block was not numbered properly");
1753 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
1754 assert(DominateeNum != 0 && "Block was not numbered properly");
1755 return DominatorNum < DominateeNum;
George Burgess IVe1100f52016-02-02 22:46:49 +00001756}
1757
George Burgess IV5f308972016-07-19 01:29:15 +00001758bool MemorySSA::dominates(const MemoryAccess *Dominator,
1759 const MemoryAccess *Dominatee) const {
1760 if (Dominator == Dominatee)
1761 return true;
1762
1763 if (isLiveOnEntryDef(Dominatee))
1764 return false;
1765
1766 if (Dominator->getBlock() != Dominatee->getBlock())
1767 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
1768 return locallyDominates(Dominator, Dominatee);
1769}
1770
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001771bool MemorySSA::dominates(const MemoryAccess *Dominator,
1772 const Use &Dominatee) const {
1773 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
1774 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
1775 // The def must dominate the incoming block of the phi.
1776 if (UseBB != Dominator->getBlock())
1777 return DT->dominates(Dominator->getBlock(), UseBB);
1778 // If the UseBB and the DefBB are the same, compare locally.
1779 return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
1780 }
1781 // If it's not a PHI node use, the normal dominates can already handle it.
1782 return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
1783}
1784
George Burgess IVe1100f52016-02-02 22:46:49 +00001785const static char LiveOnEntryStr[] = "liveOnEntry";
1786
1787void MemoryDef::print(raw_ostream &OS) const {
1788 MemoryAccess *UO = getDefiningAccess();
1789
1790 OS << getID() << " = MemoryDef(";
1791 if (UO && UO->getID())
1792 OS << UO->getID();
1793 else
1794 OS << LiveOnEntryStr;
1795 OS << ')';
1796}
1797
1798void MemoryPhi::print(raw_ostream &OS) const {
1799 bool First = true;
1800 OS << getID() << " = MemoryPhi(";
1801 for (const auto &Op : operands()) {
1802 BasicBlock *BB = getIncomingBlock(Op);
1803 MemoryAccess *MA = cast<MemoryAccess>(Op);
1804 if (!First)
1805 OS << ',';
1806 else
1807 First = false;
1808
1809 OS << '{';
1810 if (BB->hasName())
1811 OS << BB->getName();
1812 else
1813 BB->printAsOperand(OS, false);
1814 OS << ',';
1815 if (unsigned ID = MA->getID())
1816 OS << ID;
1817 else
1818 OS << LiveOnEntryStr;
1819 OS << '}';
1820 }
1821 OS << ')';
1822}
1823
1824MemoryAccess::~MemoryAccess() {}
1825
1826void MemoryUse::print(raw_ostream &OS) const {
1827 MemoryAccess *UO = getDefiningAccess();
1828 OS << "MemoryUse(";
1829 if (UO && UO->getID())
1830 OS << UO->getID();
1831 else
1832 OS << LiveOnEntryStr;
1833 OS << ')';
1834}
1835
1836void MemoryAccess::dump() const {
Daniel Berlin78cbd282017-02-20 22:26:03 +00001837// Cannot completely remove virtual function even in release mode.
Matthias Braun8c209aa2017-01-28 02:02:38 +00001838#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
George Burgess IVe1100f52016-02-02 22:46:49 +00001839 print(dbgs());
1840 dbgs() << "\n";
Matthias Braun8c209aa2017-01-28 02:02:38 +00001841#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001842}
1843
Chad Rosier232e29e2016-07-06 21:20:47 +00001844char MemorySSAPrinterLegacyPass::ID = 0;
1845
1846MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
1847 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
1848}
1849
1850void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
1851 AU.setPreservesAll();
1852 AU.addRequired<MemorySSAWrapperPass>();
1853 AU.addPreserved<MemorySSAWrapperPass>();
1854}
1855
1856bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
1857 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
1858 MSSA.print(dbgs());
1859 if (VerifyMemorySSA)
1860 MSSA.verifyMemorySSA();
1861 return false;
1862}
1863
Chandler Carruthdab4eae2016-11-23 17:53:26 +00001864AnalysisKey MemorySSAAnalysis::Key;
George Burgess IVe1100f52016-02-02 22:46:49 +00001865
Daniel Berlin1e98c042016-09-26 17:22:54 +00001866MemorySSAAnalysis::Result MemorySSAAnalysis::run(Function &F,
1867 FunctionAnalysisManager &AM) {
Geoff Berryb96d3b22016-06-01 21:30:40 +00001868 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1869 auto &AA = AM.getResult<AAManager>(F);
Geoff Berry290a13e2016-08-08 18:27:22 +00001870 return MemorySSAAnalysis::Result(make_unique<MemorySSA>(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00001871}
1872
Geoff Berryb96d3b22016-06-01 21:30:40 +00001873PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
1874 FunctionAnalysisManager &AM) {
1875 OS << "MemorySSA for function: " << F.getName() << "\n";
Geoff Berry290a13e2016-08-08 18:27:22 +00001876 AM.getResult<MemorySSAAnalysis>(F).getMSSA().print(OS);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001877
1878 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00001879}
1880
Geoff Berryb96d3b22016-06-01 21:30:40 +00001881PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
1882 FunctionAnalysisManager &AM) {
Geoff Berry290a13e2016-08-08 18:27:22 +00001883 AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001884
1885 return PreservedAnalyses::all();
1886}
1887
1888char MemorySSAWrapperPass::ID = 0;
1889
1890MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
1891 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
1892}
1893
1894void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
1895
1896void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001897 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001898 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
1899 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001900}
1901
Geoff Berryb96d3b22016-06-01 21:30:40 +00001902bool MemorySSAWrapperPass::runOnFunction(Function &F) {
1903 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1904 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1905 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00001906 return false;
1907}
1908
Geoff Berryb96d3b22016-06-01 21:30:40 +00001909void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00001910
Geoff Berryb96d3b22016-06-01 21:30:40 +00001911void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001912 MSSA->print(OS);
1913}
1914
George Burgess IVe1100f52016-02-02 22:46:49 +00001915MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
1916
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001917MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A,
1918 DominatorTree *D)
Daniel Berlind7a7ae02017-04-05 19:01:58 +00001919 : MemorySSAWalker(M), Walker(*M, *A, *D), AutoResetWalker(true) {}
George Burgess IVe1100f52016-02-02 22:46:49 +00001920
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001921MemorySSA::CachingWalker::~CachingWalker() {}
George Burgess IVe1100f52016-02-02 22:46:49 +00001922
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001923void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) {
Daniel Berlind7a7ae02017-04-05 19:01:58 +00001924 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1925 MUD->resetOptimized();
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001926}
1927
George Burgess IVe1100f52016-02-02 22:46:49 +00001928/// \brief Walk the use-def chains starting at \p MA and find
1929/// the MemoryAccess that actually clobbers Loc.
1930///
1931/// \returns our clobbering memory access
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001932MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
1933 MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +00001934 MemoryAccess *New = Walker.findClobber(StartingAccess, Q);
1935#ifdef EXPENSIVE_CHECKS
Daniel Berlind7a7ae02017-04-05 19:01:58 +00001936 MemoryAccess *NewNoCache = Walker.findClobber(StartingAccess, Q);
George Burgess IV5f308972016-07-19 01:29:15 +00001937 assert(NewNoCache == New && "Cache made us hand back a different result?");
1938#endif
1939 if (AutoResetWalker)
1940 resetClobberWalker();
1941 return New;
George Burgess IVe1100f52016-02-02 22:46:49 +00001942}
1943
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001944MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
George Burgess IV013fd732016-10-28 19:22:46 +00001945 MemoryAccess *StartingAccess, const MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001946 if (isa<MemoryPhi>(StartingAccess))
1947 return StartingAccess;
1948
1949 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
1950 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
1951 return StartingUseOrDef;
1952
1953 Instruction *I = StartingUseOrDef->getMemoryInst();
1954
1955 // Conservatively, fences are always clobbers, so don't perform the walk if we
1956 // hit a fence.
David Majnemera940f362016-07-15 17:19:24 +00001957 if (!ImmutableCallSite(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00001958 return StartingUseOrDef;
1959
1960 UpwardsMemoryQuery Q;
1961 Q.OriginalAccess = StartingUseOrDef;
1962 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00001963 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00001964 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00001965
George Burgess IVe1100f52016-02-02 22:46:49 +00001966 // Unlike the other function, do not walk to the def of a def, because we are
1967 // handed something we already believe is the clobbering access.
1968 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
1969 ? StartingUseOrDef->getDefiningAccess()
1970 : StartingUseOrDef;
1971
1972 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00001973 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
1974 DEBUG(dbgs() << *StartingUseOrDef << "\n");
1975 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
1976 DEBUG(dbgs() << *Clobber << "\n");
1977 return Clobber;
1978}
1979
1980MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00001981MemorySSA::CachingWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
1982 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
1983 // If this is a MemoryPhi, we can't do anything.
1984 if (!StartingAccess)
1985 return MA;
George Burgess IVe1100f52016-02-02 22:46:49 +00001986
Daniel Berlincd2deac2016-10-20 20:13:45 +00001987 // If this is an already optimized use or def, return the optimized result.
1988 // Note: Currently, we do not store the optimized def result because we'd need
1989 // a separate field, since we can't use it as the defining access.
Daniel Berline33bc312017-04-04 23:43:10 +00001990 if (auto *MUD = dyn_cast<MemoryUseOrDef>(StartingAccess))
1991 if (MUD->isOptimized())
1992 return MUD->getOptimized();
Daniel Berlincd2deac2016-10-20 20:13:45 +00001993
George Burgess IV400ae402016-07-20 19:51:34 +00001994 const Instruction *I = StartingAccess->getMemoryInst();
George Burgess IV5f308972016-07-19 01:29:15 +00001995 UpwardsMemoryQuery Q(I, StartingAccess);
David Majnemera940f362016-07-15 17:19:24 +00001996 // We can't sanely do anything with a fences, they conservatively
George Burgess IVe1100f52016-02-02 22:46:49 +00001997 // clobber all memory, and have no locations to get pointers from to
David Majnemera940f362016-07-15 17:19:24 +00001998 // try to disambiguate.
George Burgess IV5f308972016-07-19 01:29:15 +00001999 if (!Q.IsCall && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002000 return StartingAccess;
2001
George Burgess IV024f3d22016-08-03 19:57:02 +00002002 if (isUseTriviallyOptimizableToLiveOnEntry(*MSSA->AA, I)) {
2003 MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
Daniel Berline33bc312017-04-04 23:43:10 +00002004 if (auto *MUD = dyn_cast<MemoryUseOrDef>(StartingAccess))
2005 MUD->setOptimized(LiveOnEntry);
George Burgess IV024f3d22016-08-03 19:57:02 +00002006 return LiveOnEntry;
2007 }
2008
George Burgess IVe1100f52016-02-02 22:46:49 +00002009 // Start with the thing we already think clobbers this location
2010 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2011
2012 // At this point, DefiningAccess may be the live on entry def.
2013 // If it is, we will not get a better result.
2014 if (MSSA->isLiveOnEntryDef(DefiningAccess))
2015 return DefiningAccess;
2016
2017 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002018 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2019 DEBUG(dbgs() << *DefiningAccess << "\n");
2020 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2021 DEBUG(dbgs() << *Result << "\n");
Daniel Berline33bc312017-04-04 23:43:10 +00002022 if (auto *MUD = dyn_cast<MemoryUseOrDef>(StartingAccess))
2023 MUD->setOptimized(Result);
George Burgess IVe1100f52016-02-02 22:46:49 +00002024
2025 return Result;
2026}
2027
George Burgess IVe1100f52016-02-02 22:46:49 +00002028MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002029DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002030 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2031 return Use->getDefiningAccess();
2032 return MA;
2033}
2034
2035MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
George Burgess IV013fd732016-10-28 19:22:46 +00002036 MemoryAccess *StartingAccess, const MemoryLocation &) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002037 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2038 return Use->getDefiningAccess();
2039 return StartingAccess;
2040}
George Burgess IV5f308972016-07-19 01:29:15 +00002041} // namespace llvm