blob: 7aecda70836cd7aa0d5834b71c26cc784581117c [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");
Daniel Berlin74603a62017-04-10 18:46:00 +0000217 ImmutableCallSite UseCS(UseInst);
George Burgess IV5f308972016-07-19 01:29:15 +0000218
Daniel Berlindf101192016-08-03 00:01:46 +0000219 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
220 // These intrinsics will show up as affecting memory, but they are just
221 // markers.
222 switch (II->getIntrinsicID()) {
223 case Intrinsic::lifetime_start:
Daniel Berlin74603a62017-04-10 18:46:00 +0000224 if (UseCS)
225 return false;
226 return AA.isMustAlias(MemoryLocation(II->getArgOperand(1)), UseLoc);
Daniel Berlindf101192016-08-03 00:01:46 +0000227 case Intrinsic::lifetime_end:
228 case Intrinsic::invariant_start:
229 case Intrinsic::invariant_end:
230 case Intrinsic::assume:
231 return false;
232 default:
233 break;
234 }
235 }
236
Daniel Berlindff31de2016-08-02 21:57:52 +0000237 if (UseCS) {
238 ModRefInfo I = AA.getModRefInfo(DefInst, UseCS);
239 return I != MRI_NoModRef;
240 }
George Burgess IV82e355c2016-08-03 19:39:54 +0000241
242 if (auto *DefLoad = dyn_cast<LoadInst>(DefInst)) {
243 if (auto *UseLoad = dyn_cast<LoadInst>(UseInst)) {
244 switch (getLoadReorderability(UseLoad, DefLoad)) {
245 case Reorderability::Always:
246 return false;
247 case Reorderability::Never:
248 return true;
249 case Reorderability::IfNoAlias:
250 return !AA.isNoAlias(UseLoc, MemoryLocation::get(DefLoad));
251 }
252 }
253 }
254
Daniel Berlindff31de2016-08-02 21:57:52 +0000255 return AA.getModRefInfo(DefInst, UseLoc) & MRI_Mod;
256}
257
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000258static bool instructionClobbersQuery(MemoryDef *MD, const MemoryUseOrDef *MU,
259 const MemoryLocOrCall &UseMLOC,
260 AliasAnalysis &AA) {
261 // FIXME: This is a temporary hack to allow a single instructionClobbersQuery
262 // to exist while MemoryLocOrCall is pushed through places.
263 if (UseMLOC.IsCall)
264 return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(),
265 AA);
266 return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(),
267 AA);
268}
269
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000270// Return true when MD may alias MU, return false otherwise.
Daniel Berlindcb004f2017-03-02 23:06:46 +0000271bool MemorySSAUtil::defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
272 AliasAnalysis &AA) {
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000273 return instructionClobbersQuery(MD, MU, MemoryLocOrCall(MU), AA);
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000274}
275}
276
277namespace {
278struct UpwardsMemoryQuery {
279 // True if our original query started off as a call
280 bool IsCall;
281 // The pointer location we started the query with. This will be empty if
282 // IsCall is true.
283 MemoryLocation StartingLoc;
284 // This is the instruction we were querying about.
285 const Instruction *Inst;
286 // The MemoryAccess we actually got called with, used to test local domination
287 const MemoryAccess *OriginalAccess;
288
289 UpwardsMemoryQuery()
290 : IsCall(false), Inst(nullptr), OriginalAccess(nullptr) {}
291
292 UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
293 : IsCall(ImmutableCallSite(Inst)), Inst(Inst), OriginalAccess(Access) {
294 if (!IsCall)
295 StartingLoc = MemoryLocation::get(Inst);
296 }
297};
298
299static bool lifetimeEndsAt(MemoryDef *MD, const MemoryLocation &Loc,
300 AliasAnalysis &AA) {
301 Instruction *Inst = MD->getMemoryInst();
302 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
303 switch (II->getIntrinsicID()) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000304 case Intrinsic::lifetime_end:
305 return AA.isMustAlias(MemoryLocation(II->getArgOperand(1)), Loc);
306 default:
307 return false;
308 }
309 }
310 return false;
311}
312
313static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysis &AA,
314 const Instruction *I) {
315 // If the memory can't be changed, then loads of the memory can't be
316 // clobbered.
317 //
318 // FIXME: We should handle invariant groups, as well. It's a bit harder,
319 // because we need to pay close attention to invariant group barriers.
320 return isa<LoadInst>(I) && (I->getMetadata(LLVMContext::MD_invariant_load) ||
Hal Finkela9d67cf2017-04-09 12:57:50 +0000321 AA.pointsToConstantMemory(cast<LoadInst>(I)->
322 getPointerOperand()));
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000323}
324
George Burgess IV5f308972016-07-19 01:29:15 +0000325/// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
326/// inbetween `Start` and `ClobberAt` can clobbers `Start`.
327///
328/// This is meant to be as simple and self-contained as possible. Because it
329/// uses no cache, etc., it can be relatively expensive.
330///
331/// \param Start The MemoryAccess that we want to walk from.
332/// \param ClobberAt A clobber for Start.
333/// \param StartLoc The MemoryLocation for Start.
334/// \param MSSA The MemorySSA isntance that Start and ClobberAt belong to.
335/// \param Query The UpwardsMemoryQuery we used for our search.
336/// \param AA The AliasAnalysis we used for our search.
337static void LLVM_ATTRIBUTE_UNUSED
338checkClobberSanity(MemoryAccess *Start, MemoryAccess *ClobberAt,
339 const MemoryLocation &StartLoc, const MemorySSA &MSSA,
340 const UpwardsMemoryQuery &Query, AliasAnalysis &AA) {
341 assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
342
343 if (MSSA.isLiveOnEntryDef(Start)) {
344 assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
345 "liveOnEntry must clobber itself");
346 return;
347 }
348
George Burgess IV5f308972016-07-19 01:29:15 +0000349 bool FoundClobber = false;
350 DenseSet<MemoryAccessPair> VisitedPhis;
351 SmallVector<MemoryAccessPair, 8> Worklist;
352 Worklist.emplace_back(Start, StartLoc);
353 // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
354 // is found, complain.
355 while (!Worklist.empty()) {
356 MemoryAccessPair MAP = Worklist.pop_back_val();
357 // All we care about is that nothing from Start to ClobberAt clobbers Start.
358 // We learn nothing from revisiting nodes.
359 if (!VisitedPhis.insert(MAP).second)
360 continue;
361
362 for (MemoryAccess *MA : def_chain(MAP.first)) {
363 if (MA == ClobberAt) {
364 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
365 // instructionClobbersQuery isn't essentially free, so don't use `|=`,
366 // since it won't let us short-circuit.
367 //
368 // Also, note that this can't be hoisted out of the `Worklist` loop,
369 // since MD may only act as a clobber for 1 of N MemoryLocations.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000370 FoundClobber =
371 FoundClobber || MSSA.isLiveOnEntryDef(MD) ||
372 instructionClobbersQuery(MD, MAP.second, Query.Inst, AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000373 }
374 break;
375 }
376
377 // We should never hit liveOnEntry, unless it's the clobber.
378 assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
379
380 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
381 (void)MD;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000382 assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA) &&
George Burgess IV5f308972016-07-19 01:29:15 +0000383 "Found clobber before reaching ClobberAt!");
384 continue;
385 }
386
387 assert(isa<MemoryPhi>(MA));
388 Worklist.append(upward_defs_begin({MA, MAP.second}), upward_defs_end());
389 }
390 }
391
392 // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
393 // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
394 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
395 "ClobberAt never acted as a clobber");
396}
397
398/// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
399/// in one class.
400class ClobberWalker {
401 /// Save a few bytes by using unsigned instead of size_t.
402 using ListIndex = unsigned;
403
404 /// Represents a span of contiguous MemoryDefs, potentially ending in a
405 /// MemoryPhi.
406 struct DefPath {
407 MemoryLocation Loc;
408 // Note that, because we always walk in reverse, Last will always dominate
409 // First. Also note that First and Last are inclusive.
410 MemoryAccess *First;
411 MemoryAccess *Last;
George Burgess IV5f308972016-07-19 01:29:15 +0000412 Optional<ListIndex> Previous;
413
414 DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
415 Optional<ListIndex> Previous)
416 : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
417
418 DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
419 Optional<ListIndex> Previous)
420 : DefPath(Loc, Init, Init, Previous) {}
421 };
422
423 const MemorySSA &MSSA;
424 AliasAnalysis &AA;
425 DominatorTree &DT;
George Burgess IV5f308972016-07-19 01:29:15 +0000426 UpwardsMemoryQuery *Query;
George Burgess IV5f308972016-07-19 01:29:15 +0000427
428 // Phi optimization bookkeeping
429 SmallVector<DefPath, 32> Paths;
430 DenseSet<ConstMemoryAccessPair> VisitedPhis;
George Burgess IV5f308972016-07-19 01:29:15 +0000431
George Burgess IV5f308972016-07-19 01:29:15 +0000432 /// Find the nearest def or phi that `From` can legally be optimized to.
Daniel Berlind0420312017-04-01 09:01:12 +0000433 const MemoryAccess *getWalkTarget(const MemoryPhi *From) const {
George Burgess IV5f308972016-07-19 01:29:15 +0000434 assert(From->getNumOperands() && "Phi with no operands?");
435
436 BasicBlock *BB = From->getBlock();
George Burgess IV5f308972016-07-19 01:29:15 +0000437 MemoryAccess *Result = MSSA.getLiveOnEntryDef();
438 DomTreeNode *Node = DT.getNode(BB);
439 while ((Node = Node->getIDom())) {
Daniel Berlin7500c562017-04-01 08:59:45 +0000440 auto *Defs = MSSA.getBlockDefs(Node->getBlock());
441 if (Defs)
Daniel Berlind0420312017-04-01 09:01:12 +0000442 return &*Defs->rbegin();
George Burgess IV5f308972016-07-19 01:29:15 +0000443 }
George Burgess IV5f308972016-07-19 01:29:15 +0000444 return Result;
445 }
446
447 /// Result of calling walkToPhiOrClobber.
448 struct UpwardsWalkResult {
449 /// The "Result" of the walk. Either a clobber, the last thing we walked, or
450 /// both.
451 MemoryAccess *Result;
452 bool IsKnownClobber;
George Burgess IV5f308972016-07-19 01:29:15 +0000453 };
454
455 /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
456 /// This will update Desc.Last as it walks. It will (optionally) also stop at
457 /// StopAt.
458 ///
459 /// This does not test for whether StopAt is a clobber
Daniel Berlind0420312017-04-01 09:01:12 +0000460 UpwardsWalkResult
461 walkToPhiOrClobber(DefPath &Desc,
462 const MemoryAccess *StopAt = nullptr) const {
George Burgess IV5f308972016-07-19 01:29:15 +0000463 assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
464
465 for (MemoryAccess *Current : def_chain(Desc.Last)) {
466 Desc.Last = Current;
467 if (Current == StopAt)
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000468 return {Current, false};
George Burgess IV5f308972016-07-19 01:29:15 +0000469
470 if (auto *MD = dyn_cast<MemoryDef>(Current))
471 if (MSSA.isLiveOnEntryDef(MD) ||
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000472 instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA))
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000473 return {MD, true};
George Burgess IV5f308972016-07-19 01:29:15 +0000474 }
475
476 assert(isa<MemoryPhi>(Desc.Last) &&
477 "Ended at a non-clobber that's not a phi?");
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000478 return {Desc.Last, false};
George Burgess IV5f308972016-07-19 01:29:15 +0000479 }
480
481 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
482 ListIndex PriorNode) {
483 auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),
484 upward_defs_end());
485 for (const MemoryAccessPair &P : UpwardDefs) {
486 PausedSearches.push_back(Paths.size());
487 Paths.emplace_back(P.second, P.first, PriorNode);
488 }
489 }
490
491 /// Represents a search that terminated after finding a clobber. This clobber
492 /// may or may not be present in the path of defs from LastNode..SearchStart,
493 /// since it may have been retrieved from cache.
494 struct TerminatedPath {
495 MemoryAccess *Clobber;
496 ListIndex LastNode;
497 };
498
499 /// Get an access that keeps us from optimizing to the given phi.
500 ///
501 /// PausedSearches is an array of indices into the Paths array. Its incoming
502 /// value is the indices of searches that stopped at the last phi optimization
503 /// target. It's left in an unspecified state.
504 ///
505 /// If this returns None, NewPaused is a vector of searches that terminated
506 /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
George Burgess IV14633b52016-08-03 01:22:19 +0000507 Optional<TerminatedPath>
Daniel Berlind0420312017-04-01 09:01:12 +0000508 getBlockingAccess(const MemoryAccess *StopWhere,
George Burgess IV5f308972016-07-19 01:29:15 +0000509 SmallVectorImpl<ListIndex> &PausedSearches,
510 SmallVectorImpl<ListIndex> &NewPaused,
511 SmallVectorImpl<TerminatedPath> &Terminated) {
512 assert(!PausedSearches.empty() && "No searches to continue?");
513
514 // BFS vs DFS really doesn't make a difference here, so just do a DFS with
515 // PausedSearches as our stack.
516 while (!PausedSearches.empty()) {
517 ListIndex PathIndex = PausedSearches.pop_back_val();
518 DefPath &Node = Paths[PathIndex];
519
520 // If we've already visited this path with this MemoryLocation, we don't
521 // need to do so again.
522 //
523 // NOTE: That we just drop these paths on the ground makes caching
524 // behavior sporadic. e.g. given a diamond:
525 // A
526 // B C
527 // D
528 //
529 // ...If we walk D, B, A, C, we'll only cache the result of phi
530 // optimization for A, B, and D; C will be skipped because it dies here.
531 // This arguably isn't the worst thing ever, since:
532 // - We generally query things in a top-down order, so if we got below D
533 // without needing cache entries for {C, MemLoc}, then chances are
534 // that those cache entries would end up ultimately unused.
535 // - We still cache things for A, so C only needs to walk up a bit.
536 // If this behavior becomes problematic, we can fix without a ton of extra
537 // work.
538 if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
539 continue;
540
541 UpwardsWalkResult Res = walkToPhiOrClobber(Node, /*StopAt=*/StopWhere);
542 if (Res.IsKnownClobber) {
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000543 assert(Res.Result != StopWhere);
George Burgess IV5f308972016-07-19 01:29:15 +0000544 // If this wasn't a cache hit, we hit a clobber when walking. That's a
545 // failure.
George Burgess IV14633b52016-08-03 01:22:19 +0000546 TerminatedPath Term{Res.Result, PathIndex};
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000547 if (!MSSA.dominates(Res.Result, StopWhere))
George Burgess IV14633b52016-08-03 01:22:19 +0000548 return Term;
George Burgess IV5f308972016-07-19 01:29:15 +0000549
550 // Otherwise, it's a valid thing to potentially optimize to.
George Burgess IV14633b52016-08-03 01:22:19 +0000551 Terminated.push_back(Term);
George Burgess IV5f308972016-07-19 01:29:15 +0000552 continue;
553 }
554
555 if (Res.Result == StopWhere) {
556 // We've hit our target. Save this path off for if we want to continue
557 // walking.
558 NewPaused.push_back(PathIndex);
559 continue;
560 }
561
562 assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
563 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
564 }
565
566 return None;
567 }
568
569 template <typename T, typename Walker>
570 struct generic_def_path_iterator
571 : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
572 std::forward_iterator_tag, T *> {
573 generic_def_path_iterator() : W(nullptr), N(None) {}
574 generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
575
576 T &operator*() const { return curNode(); }
577
578 generic_def_path_iterator &operator++() {
579 N = curNode().Previous;
580 return *this;
581 }
582
583 bool operator==(const generic_def_path_iterator &O) const {
584 if (N.hasValue() != O.N.hasValue())
585 return false;
586 return !N.hasValue() || *N == *O.N;
587 }
588
589 private:
590 T &curNode() const { return W->Paths[*N]; }
591
592 Walker *W;
593 Optional<ListIndex> N;
594 };
595
596 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
597 using const_def_path_iterator =
598 generic_def_path_iterator<const DefPath, const ClobberWalker>;
599
600 iterator_range<def_path_iterator> def_path(ListIndex From) {
601 return make_range(def_path_iterator(this, From), def_path_iterator());
602 }
603
604 iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
605 return make_range(const_def_path_iterator(this, From),
606 const_def_path_iterator());
607 }
608
609 struct OptznResult {
610 /// The path that contains our result.
611 TerminatedPath PrimaryClobber;
612 /// The paths that we can legally cache back from, but that aren't
613 /// necessarily the result of the Phi optimization.
614 SmallVector<TerminatedPath, 4> OtherClobbers;
615 };
616
617 ListIndex defPathIndex(const DefPath &N) const {
618 // The assert looks nicer if we don't need to do &N
619 const DefPath *NP = &N;
620 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
621 "Out of bounds DefPath!");
622 return NP - &Paths.front();
623 }
624
625 /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
626 /// that act as legal clobbers. Note that this won't return *all* clobbers.
627 ///
628 /// Phi optimization algorithm tl;dr:
629 /// - Find the earliest def/phi, A, we can optimize to
630 /// - Find if all paths from the starting memory access ultimately reach A
631 /// - If not, optimization isn't possible.
632 /// - Otherwise, walk from A to another clobber or phi, A'.
633 /// - If A' is a def, we're done.
634 /// - If A' is a phi, try to optimize it.
635 ///
636 /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
637 /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
638 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
639 const MemoryLocation &Loc) {
640 assert(Paths.empty() && VisitedPhis.empty() &&
641 "Reset the optimization state.");
642
643 Paths.emplace_back(Loc, Start, Phi, None);
644 // Stores how many "valid" optimization nodes we had prior to calling
645 // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
646 auto PriorPathsSize = Paths.size();
647
648 SmallVector<ListIndex, 16> PausedSearches;
649 SmallVector<ListIndex, 8> NewPaused;
650 SmallVector<TerminatedPath, 4> TerminatedPaths;
651
652 addSearches(Phi, PausedSearches, 0);
653
654 // Moves the TerminatedPath with the "most dominated" Clobber to the end of
655 // Paths.
656 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
657 assert(!Paths.empty() && "Need a path to move");
George Burgess IV5f308972016-07-19 01:29:15 +0000658 auto Dom = Paths.begin();
659 for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
660 if (!MSSA.dominates(I->Clobber, Dom->Clobber))
661 Dom = I;
662 auto Last = Paths.end() - 1;
663 if (Last != Dom)
664 std::iter_swap(Last, Dom);
665 };
666
667 MemoryPhi *Current = Phi;
668 while (1) {
669 assert(!MSSA.isLiveOnEntryDef(Current) &&
670 "liveOnEntry wasn't treated as a clobber?");
671
Daniel Berlind0420312017-04-01 09:01:12 +0000672 const auto *Target = getWalkTarget(Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000673 // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
674 // optimization for the prior phi.
675 assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
676 return MSSA.dominates(P.Clobber, Target);
677 }));
678
679 // FIXME: This is broken, because the Blocker may be reported to be
680 // liveOnEntry, and we'll happily wait for that to disappear (read: never)
George Burgess IV7f414b92016-08-22 23:40:01 +0000681 // For the moment, this is fine, since we do nothing with blocker info.
George Burgess IV14633b52016-08-03 01:22:19 +0000682 if (Optional<TerminatedPath> Blocker = getBlockingAccess(
George Burgess IV5f308972016-07-19 01:29:15 +0000683 Target, PausedSearches, NewPaused, TerminatedPaths)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000684
685 // Find the node we started at. We can't search based on N->Last, since
686 // we may have gone around a loop with a different MemoryLocation.
George Burgess IV14633b52016-08-03 01:22:19 +0000687 auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
George Burgess IV5f308972016-07-19 01:29:15 +0000688 return defPathIndex(N) < PriorPathsSize;
689 });
690 assert(Iter != def_path_iterator());
691
692 DefPath &CurNode = *Iter;
693 assert(CurNode.Last == Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000694
695 // Two things:
696 // A. We can't reliably cache all of NewPaused back. Consider a case
697 // where we have two paths in NewPaused; one of which can't optimize
698 // above this phi, whereas the other can. If we cache the second path
699 // back, we'll end up with suboptimal cache entries. We can handle
700 // cases like this a bit better when we either try to find all
701 // clobbers that block phi optimization, or when our cache starts
702 // supporting unfinished searches.
703 // B. We can't reliably cache TerminatedPaths back here without doing
704 // extra checks; consider a case like:
705 // T
706 // / \
707 // D C
708 // \ /
709 // S
710 // Where T is our target, C is a node with a clobber on it, D is a
711 // diamond (with a clobber *only* on the left or right node, N), and
712 // S is our start. Say we walk to D, through the node opposite N
713 // (read: ignoring the clobber), and see a cache entry in the top
714 // node of D. That cache entry gets put into TerminatedPaths. We then
715 // walk up to C (N is later in our worklist), find the clobber, and
716 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
717 // the bottom part of D to the cached clobber, ignoring the clobber
718 // in N. Again, this problem goes away if we start tracking all
719 // blockers for a given phi optimization.
720 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
721 return {Result, {}};
722 }
723
724 // If there's nothing left to search, then all paths led to valid clobbers
725 // that we got from our cache; pick the nearest to the start, and allow
726 // the rest to be cached back.
727 if (NewPaused.empty()) {
728 MoveDominatedPathToEnd(TerminatedPaths);
729 TerminatedPath Result = TerminatedPaths.pop_back_val();
730 return {Result, std::move(TerminatedPaths)};
731 }
732
733 MemoryAccess *DefChainEnd = nullptr;
734 SmallVector<TerminatedPath, 4> Clobbers;
735 for (ListIndex Paused : NewPaused) {
736 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
737 if (WR.IsKnownClobber)
738 Clobbers.push_back({WR.Result, Paused});
739 else
740 // Micro-opt: If we hit the end of the chain, save it.
741 DefChainEnd = WR.Result;
742 }
743
744 if (!TerminatedPaths.empty()) {
745 // If we couldn't find the dominating phi/liveOnEntry in the above loop,
746 // do it now.
747 if (!DefChainEnd)
Daniel Berlind0420312017-04-01 09:01:12 +0000748 for (auto *MA : def_chain(const_cast<MemoryAccess *>(Target)))
George Burgess IV5f308972016-07-19 01:29:15 +0000749 DefChainEnd = MA;
750
751 // If any of the terminated paths don't dominate the phi we'll try to
752 // optimize, we need to figure out what they are and quit.
753 const BasicBlock *ChainBB = DefChainEnd->getBlock();
754 for (const TerminatedPath &TP : TerminatedPaths) {
755 // Because we know that DefChainEnd is as "high" as we can go, we
756 // don't need local dominance checks; BB dominance is sufficient.
757 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
758 Clobbers.push_back(TP);
759 }
760 }
761
762 // If we have clobbers in the def chain, find the one closest to Current
763 // and quit.
764 if (!Clobbers.empty()) {
765 MoveDominatedPathToEnd(Clobbers);
766 TerminatedPath Result = Clobbers.pop_back_val();
767 return {Result, std::move(Clobbers)};
768 }
769
770 assert(all_of(NewPaused,
771 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
772
773 // Because liveOnEntry is a clobber, this must be a phi.
774 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
775
776 PriorPathsSize = Paths.size();
777 PausedSearches.clear();
778 for (ListIndex I : NewPaused)
779 addSearches(DefChainPhi, PausedSearches, I);
780 NewPaused.clear();
781
782 Current = DefChainPhi;
783 }
784 }
785
George Burgess IV5f308972016-07-19 01:29:15 +0000786 void verifyOptResult(const OptznResult &R) const {
787 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
788 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
789 }));
790 }
791
792 void resetPhiOptznState() {
793 Paths.clear();
794 VisitedPhis.clear();
795 }
796
797public:
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000798 ClobberWalker(const MemorySSA &MSSA, AliasAnalysis &AA, DominatorTree &DT)
799 : MSSA(MSSA), AA(AA), DT(DT) {}
George Burgess IV5f308972016-07-19 01:29:15 +0000800
Daniel Berlin7500c562017-04-01 08:59:45 +0000801 void reset() {}
George Burgess IV5f308972016-07-19 01:29:15 +0000802
803 /// Finds the nearest clobber for the given query, optimizing phis if
804 /// possible.
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000805 MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +0000806 Query = &Q;
807
808 MemoryAccess *Current = Start;
809 // This walker pretends uses don't exist. If we're handed one, silently grab
810 // its def. (This has the nice side-effect of ensuring we never cache uses)
811 if (auto *MU = dyn_cast<MemoryUse>(Start))
812 Current = MU->getDefiningAccess();
813
814 DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
815 // Fast path for the overly-common case (no crazy phi optimization
816 // necessary)
817 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000818 MemoryAccess *Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000819 if (WalkResult.IsKnownClobber) {
George Burgess IV93ea19b2016-07-24 07:03:49 +0000820 Result = WalkResult.Result;
821 } else {
822 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
823 Current, Q.StartingLoc);
824 verifyOptResult(OptRes);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000825 resetPhiOptznState();
826 Result = OptRes.PrimaryClobber.Clobber;
George Burgess IV5f308972016-07-19 01:29:15 +0000827 }
828
George Burgess IV5f308972016-07-19 01:29:15 +0000829#ifdef EXPENSIVE_CHECKS
George Burgess IV93ea19b2016-07-24 07:03:49 +0000830 checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000831#endif
George Burgess IV93ea19b2016-07-24 07:03:49 +0000832 return Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000833 }
Geoff Berrycdf53332016-08-08 17:52:01 +0000834
835 void verify(const MemorySSA *MSSA) { assert(MSSA == &this->MSSA); }
George Burgess IV5f308972016-07-19 01:29:15 +0000836};
837
838struct RenamePassData {
839 DomTreeNode *DTN;
840 DomTreeNode::const_iterator ChildIt;
841 MemoryAccess *IncomingVal;
842
843 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
844 MemoryAccess *M)
845 : DTN(D), ChildIt(It), IncomingVal(M) {}
846 void swap(RenamePassData &RHS) {
847 std::swap(DTN, RHS.DTN);
848 std::swap(ChildIt, RHS.ChildIt);
849 std::swap(IncomingVal, RHS.IncomingVal);
850 }
851};
852} // anonymous namespace
853
854namespace llvm {
Daniel Berlind952cea2017-04-07 01:28:36 +0000855/// \brief A MemorySSAWalker that does AA walks to disambiguate accesses. It no
856/// longer does caching on its own,
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000857/// but the name has been retained for the moment.
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000858class MemorySSA::CachingWalker final : public MemorySSAWalker {
George Burgess IV5f308972016-07-19 01:29:15 +0000859 ClobberWalker Walker;
860 bool AutoResetWalker;
861
862 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, UpwardsMemoryQuery &);
863 void verifyRemoved(MemoryAccess *);
864
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000865public:
866 CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *);
867 ~CachingWalker() override;
868
George Burgess IV400ae402016-07-20 19:51:34 +0000869 using MemorySSAWalker::getClobberingMemoryAccess;
870 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override;
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000871 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
George Burgess IV013fd732016-10-28 19:22:46 +0000872 const MemoryLocation &) override;
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000873 void invalidateInfo(MemoryAccess *) override;
874
George Burgess IV5f308972016-07-19 01:29:15 +0000875 /// Whether we call resetClobberWalker() after each time we *actually* walk to
876 /// answer a clobber query.
877 void setAutoResetWalker(bool AutoReset) { AutoResetWalker = AutoReset; }
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000878
Daniel Berlin7500c562017-04-01 08:59:45 +0000879 /// Drop the walker's persistent data structures.
George Burgess IV5f308972016-07-19 01:29:15 +0000880 void resetClobberWalker() { Walker.reset(); }
Geoff Berrycdf53332016-08-08 17:52:01 +0000881
882 void verify(const MemorySSA *MSSA) override {
883 MemorySSAWalker::verify(MSSA);
884 Walker.verify(MSSA);
885 }
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000886};
George Burgess IVe1100f52016-02-02 22:46:49 +0000887
Daniel Berlin78cbd282017-02-20 22:26:03 +0000888void MemorySSA::renameSuccessorPhis(BasicBlock *BB, MemoryAccess *IncomingVal,
889 bool RenameAllUses) {
George Burgess IVe1100f52016-02-02 22:46:49 +0000890 // Pass through values to our successors
891 for (const BasicBlock *S : successors(BB)) {
892 auto It = PerBlockAccesses.find(S);
893 // Rename the phi nodes in our successor block
894 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
895 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +0000896 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000897 auto *Phi = cast<MemoryPhi>(&Accesses->front());
Daniel Berlin78cbd282017-02-20 22:26:03 +0000898 if (RenameAllUses) {
899 int PhiIndex = Phi->getBasicBlockIndex(BB);
900 assert(PhiIndex != -1 && "Incomplete phi during partial rename");
901 Phi->setIncomingValue(PhiIndex, IncomingVal);
902 } else
903 Phi->addIncoming(IncomingVal, BB);
George Burgess IVe1100f52016-02-02 22:46:49 +0000904 }
Daniel Berlin78cbd282017-02-20 22:26:03 +0000905}
George Burgess IVe1100f52016-02-02 22:46:49 +0000906
Daniel Berlin78cbd282017-02-20 22:26:03 +0000907/// \brief Rename a single basic block into MemorySSA form.
908/// Uses the standard SSA renaming algorithm.
909/// \returns The new incoming value.
910MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB, MemoryAccess *IncomingVal,
911 bool RenameAllUses) {
912 auto It = PerBlockAccesses.find(BB);
913 // Skip most processing if the list is empty.
914 if (It != PerBlockAccesses.end()) {
915 AccessList *Accesses = It->second.get();
916 for (MemoryAccess &L : *Accesses) {
917 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) {
918 if (MUD->getDefiningAccess() == nullptr || RenameAllUses)
919 MUD->setDefiningAccess(IncomingVal);
920 if (isa<MemoryDef>(&L))
921 IncomingVal = &L;
922 } else {
923 IncomingVal = &L;
924 }
925 }
926 }
George Burgess IVe1100f52016-02-02 22:46:49 +0000927 return IncomingVal;
928}
929
930/// \brief This is the standard SSA renaming algorithm.
931///
932/// We walk the dominator tree in preorder, renaming accesses, and then filling
933/// in phi nodes in our successors.
934void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
Daniel Berlin78cbd282017-02-20 22:26:03 +0000935 SmallPtrSetImpl<BasicBlock *> &Visited,
936 bool SkipVisited, bool RenameAllUses) {
George Burgess IVe1100f52016-02-02 22:46:49 +0000937 SmallVector<RenamePassData, 32> WorkStack;
Daniel Berlin78cbd282017-02-20 22:26:03 +0000938 // Skip everything if we already renamed this block and we are skipping.
939 // Note: You can't sink this into the if, because we need it to occur
940 // regardless of whether we skip blocks or not.
941 bool AlreadyVisited = !Visited.insert(Root->getBlock()).second;
942 if (SkipVisited && AlreadyVisited)
943 return;
944
945 IncomingVal = renameBlock(Root->getBlock(), IncomingVal, RenameAllUses);
946 renameSuccessorPhis(Root->getBlock(), IncomingVal, RenameAllUses);
George Burgess IVe1100f52016-02-02 22:46:49 +0000947 WorkStack.push_back({Root, Root->begin(), IncomingVal});
George Burgess IVe1100f52016-02-02 22:46:49 +0000948
949 while (!WorkStack.empty()) {
950 DomTreeNode *Node = WorkStack.back().DTN;
951 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
952 IncomingVal = WorkStack.back().IncomingVal;
953
954 if (ChildIt == Node->end()) {
955 WorkStack.pop_back();
956 } else {
957 DomTreeNode *Child = *ChildIt;
958 ++WorkStack.back().ChildIt;
959 BasicBlock *BB = Child->getBlock();
Daniel Berlin78cbd282017-02-20 22:26:03 +0000960 // Note: You can't sink this into the if, because we need it to occur
961 // regardless of whether we skip blocks or not.
962 AlreadyVisited = !Visited.insert(BB).second;
963 if (SkipVisited && AlreadyVisited) {
964 // We already visited this during our renaming, which can happen when
965 // being asked to rename multiple blocks. Figure out the incoming val,
966 // which is the last def.
967 // Incoming value can only change if there is a block def, and in that
968 // case, it's the last block def in the list.
969 if (auto *BlockDefs = getWritableBlockDefs(BB))
970 IncomingVal = &*BlockDefs->rbegin();
971 } else
972 IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses);
973 renameSuccessorPhis(BB, IncomingVal, RenameAllUses);
George Burgess IVe1100f52016-02-02 22:46:49 +0000974 WorkStack.push_back({Child, Child->begin(), IncomingVal});
975 }
976 }
977}
978
979/// \brief Compute dominator levels, used by the phi insertion algorithm above.
980void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) {
981 for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode());
982 DFI != DFE; ++DFI)
983 DomLevels[*DFI] = DFI.getPathLength() - 1;
984}
985
George Burgess IVa362b092016-07-06 00:28:43 +0000986/// \brief This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +0000987/// unreachable blocks, and marking all other unreachable MemoryAccess's as
988/// being uses of the live on entry definition.
989void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
990 assert(!DT->isReachableFromEntry(BB) &&
991 "Reachable block found while handling unreachable blocks");
992
Daniel Berlinfc7e6512016-07-06 05:32:05 +0000993 // Make sure phi nodes in our reachable successors end up with a
994 // LiveOnEntryDef for our incoming edge, even though our block is forward
995 // unreachable. We could just disconnect these blocks from the CFG fully,
996 // but we do not right now.
997 for (const BasicBlock *S : successors(BB)) {
998 if (!DT->isReachableFromEntry(S))
999 continue;
1000 auto It = PerBlockAccesses.find(S);
1001 // Rename the phi nodes in our successor block
1002 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1003 continue;
1004 AccessList *Accesses = It->second.get();
1005 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1006 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1007 }
1008
George Burgess IVe1100f52016-02-02 22:46:49 +00001009 auto It = PerBlockAccesses.find(BB);
1010 if (It == PerBlockAccesses.end())
1011 return;
1012
1013 auto &Accesses = It->second;
1014 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1015 auto Next = std::next(AI);
1016 // If we have a phi, just remove it. We are going to replace all
1017 // users with live on entry.
1018 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1019 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1020 else
1021 Accesses->erase(AI);
1022 AI = Next;
1023 }
1024}
1025
Geoff Berryb96d3b22016-06-01 21:30:40 +00001026MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
1027 : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
Daniel Berlincd2deac2016-10-20 20:13:45 +00001028 NextID(INVALID_MEMORYACCESS_ID) {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001029 buildMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001030}
1031
George Burgess IVe1100f52016-02-02 22:46:49 +00001032MemorySSA::~MemorySSA() {
1033 // Drop all our references
1034 for (const auto &Pair : PerBlockAccesses)
1035 for (MemoryAccess &MA : *Pair.second)
1036 MA.dropAllReferences();
1037}
1038
Daniel Berlin14300262016-06-21 18:39:20 +00001039MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001040 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1041
1042 if (Res.second)
Daniel Berlinada263d2016-06-20 20:21:33 +00001043 Res.first->second = make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001044 return Res.first->second.get();
1045}
Daniel Berlind602e042017-01-25 20:56:19 +00001046MemorySSA::DefsList *MemorySSA::getOrCreateDefsList(const BasicBlock *BB) {
1047 auto Res = PerBlockDefs.insert(std::make_pair(BB, nullptr));
1048
1049 if (Res.second)
1050 Res.first->second = make_unique<DefsList>();
1051 return Res.first->second.get();
1052}
George Burgess IVe1100f52016-02-02 22:46:49 +00001053
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001054/// This class is a batch walker of all MemoryUse's in the program, and points
1055/// their defining access at the thing that actually clobbers them. Because it
1056/// is a batch walker that touches everything, it does not operate like the
1057/// other walkers. This walker is basically performing a top-down SSA renaming
1058/// pass, where the version stack is used as the cache. This enables it to be
1059/// significantly more time and memory efficient than using the regular walker,
1060/// which is walking bottom-up.
1061class MemorySSA::OptimizeUses {
1062public:
1063 OptimizeUses(MemorySSA *MSSA, MemorySSAWalker *Walker, AliasAnalysis *AA,
1064 DominatorTree *DT)
1065 : MSSA(MSSA), Walker(Walker), AA(AA), DT(DT) {
1066 Walker = MSSA->getWalker();
1067 }
1068
1069 void optimizeUses();
1070
1071private:
1072 /// This represents where a given memorylocation is in the stack.
1073 struct MemlocStackInfo {
1074 // This essentially is keeping track of versions of the stack. Whenever
1075 // the stack changes due to pushes or pops, these versions increase.
1076 unsigned long StackEpoch;
1077 unsigned long PopEpoch;
1078 // This is the lower bound of places on the stack to check. It is equal to
1079 // the place the last stack walk ended.
1080 // Note: Correctness depends on this being initialized to 0, which densemap
1081 // does
1082 unsigned long LowerBound;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001083 const BasicBlock *LowerBoundBlock;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001084 // This is where the last walk for this memory location ended.
1085 unsigned long LastKill;
1086 bool LastKillValid;
1087 };
1088 void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1089 SmallVectorImpl<MemoryAccess *> &,
1090 DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
1091 MemorySSA *MSSA;
1092 MemorySSAWalker *Walker;
1093 AliasAnalysis *AA;
1094 DominatorTree *DT;
1095};
1096
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001097/// Optimize the uses in a given block This is basically the SSA renaming
1098/// algorithm, with one caveat: We are able to use a single stack for all
1099/// MemoryUses. This is because the set of *possible* reaching MemoryDefs is
1100/// the same for every MemoryUse. The *actual* clobbering MemoryDef is just
1101/// going to be some position in that stack of possible ones.
1102///
1103/// We track the stack positions that each MemoryLocation needs
1104/// to check, and last ended at. This is because we only want to check the
1105/// things that changed since last time. The same MemoryLocation should
1106/// get clobbered by the same store (getModRefInfo does not use invariantness or
1107/// things like this, and if they start, we can modify MemoryLocOrCall to
1108/// include relevant data)
1109void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1110 const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1111 SmallVectorImpl<MemoryAccess *> &VersionStack,
1112 DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
1113
1114 /// If no accesses, nothing to do.
1115 MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
1116 if (Accesses == nullptr)
1117 return;
1118
1119 // Pop everything that doesn't dominate the current block off the stack,
1120 // increment the PopEpoch to account for this.
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001121 while (true) {
1122 assert(
1123 !VersionStack.empty() &&
1124 "Version stack should have liveOnEntry sentinel dominating everything");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001125 BasicBlock *BackBlock = VersionStack.back()->getBlock();
1126 if (DT->dominates(BackBlock, BB))
1127 break;
1128 while (VersionStack.back()->getBlock() == BackBlock)
1129 VersionStack.pop_back();
1130 ++PopEpoch;
1131 }
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001132
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001133 for (MemoryAccess &MA : *Accesses) {
1134 auto *MU = dyn_cast<MemoryUse>(&MA);
1135 if (!MU) {
1136 VersionStack.push_back(&MA);
1137 ++StackEpoch;
1138 continue;
1139 }
1140
George Burgess IV024f3d22016-08-03 19:57:02 +00001141 if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
Daniel Berlincd2deac2016-10-20 20:13:45 +00001142 MU->setDefiningAccess(MSSA->getLiveOnEntryDef(), true);
George Burgess IV024f3d22016-08-03 19:57:02 +00001143 continue;
1144 }
1145
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001146 MemoryLocOrCall UseMLOC(MU);
1147 auto &LocInfo = LocStackInfo[UseMLOC];
Daniel Berlin26fcea92016-08-02 20:02:21 +00001148 // If the pop epoch changed, it means we've removed stuff from top of
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001149 // stack due to changing blocks. We may have to reset the lower bound or
1150 // last kill info.
1151 if (LocInfo.PopEpoch != PopEpoch) {
1152 LocInfo.PopEpoch = PopEpoch;
1153 LocInfo.StackEpoch = StackEpoch;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001154 // If the lower bound was in something that no longer dominates us, we
1155 // have to reset it.
1156 // We can't simply track stack size, because the stack may have had
1157 // pushes/pops in the meantime.
1158 // XXX: This is non-optimal, but only is slower cases with heavily
1159 // branching dominator trees. To get the optimal number of queries would
1160 // be to make lowerbound and lastkill a per-loc stack, and pop it until
1161 // the top of that stack dominates us. This does not seem worth it ATM.
1162 // A much cheaper optimization would be to always explore the deepest
1163 // branch of the dominator tree first. This will guarantee this resets on
1164 // the smallest set of blocks.
1165 if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
Daniel Berlin1e98c042016-09-26 17:22:54 +00001166 !DT->dominates(LocInfo.LowerBoundBlock, BB)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001167 // Reset the lower bound of things to check.
1168 // TODO: Some day we should be able to reset to last kill, rather than
1169 // 0.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001170 LocInfo.LowerBound = 0;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001171 LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001172 LocInfo.LastKillValid = false;
1173 }
1174 } else if (LocInfo.StackEpoch != StackEpoch) {
1175 // If all that has changed is the StackEpoch, we only have to check the
1176 // new things on the stack, because we've checked everything before. In
1177 // this case, the lower bound of things to check remains the same.
1178 LocInfo.PopEpoch = PopEpoch;
1179 LocInfo.StackEpoch = StackEpoch;
1180 }
1181 if (!LocInfo.LastKillValid) {
1182 LocInfo.LastKill = VersionStack.size() - 1;
1183 LocInfo.LastKillValid = true;
1184 }
1185
1186 // At this point, we should have corrected last kill and LowerBound to be
1187 // in bounds.
1188 assert(LocInfo.LowerBound < VersionStack.size() &&
1189 "Lower bound out of range");
1190 assert(LocInfo.LastKill < VersionStack.size() &&
1191 "Last kill info out of range");
1192 // In any case, the new upper bound is the top of the stack.
1193 unsigned long UpperBound = VersionStack.size() - 1;
1194
1195 if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
Daniel Berlin26fcea92016-08-02 20:02:21 +00001196 DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
1197 << *(MU->getMemoryInst()) << ")"
1198 << " because there are " << UpperBound - LocInfo.LowerBound
1199 << " stores to disambiguate\n");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001200 // Because we did not walk, LastKill is no longer valid, as this may
1201 // have been a kill.
1202 LocInfo.LastKillValid = false;
1203 continue;
1204 }
1205 bool FoundClobberResult = false;
1206 while (UpperBound > LocInfo.LowerBound) {
1207 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1208 // For phis, use the walker, see where we ended up, go there
1209 Instruction *UseInst = MU->getMemoryInst();
1210 MemoryAccess *Result = Walker->getClobberingMemoryAccess(UseInst);
1211 // We are guaranteed to find it or something is wrong
1212 while (VersionStack[UpperBound] != Result) {
1213 assert(UpperBound != 0);
1214 --UpperBound;
1215 }
1216 FoundClobberResult = true;
1217 break;
1218 }
1219
1220 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
Daniel Berlindf101192016-08-03 00:01:46 +00001221 // If the lifetime of the pointer ends at this instruction, it's live on
1222 // entry.
1223 if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1224 // Reset UpperBound to liveOnEntryDef's place in the stack
1225 UpperBound = 0;
1226 FoundClobberResult = true;
1227 break;
1228 }
Daniel Berlindff31de2016-08-02 21:57:52 +00001229 if (instructionClobbersQuery(MD, MU, UseMLOC, *AA)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001230 FoundClobberResult = true;
1231 break;
1232 }
1233 --UpperBound;
1234 }
1235 // At the end of this loop, UpperBound is either a clobber, or lower bound
1236 // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1237 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
Daniel Berlincd2deac2016-10-20 20:13:45 +00001238 MU->setDefiningAccess(VersionStack[UpperBound], true);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001239 // We were last killed now by where we got to
1240 LocInfo.LastKill = UpperBound;
1241 } else {
1242 // Otherwise, we checked all the new ones, and now we know we can get to
1243 // LastKill.
Daniel Berlincd2deac2016-10-20 20:13:45 +00001244 MU->setDefiningAccess(VersionStack[LocInfo.LastKill], true);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001245 }
1246 LocInfo.LowerBound = VersionStack.size() - 1;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001247 LocInfo.LowerBoundBlock = BB;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001248 }
1249}
1250
1251/// Optimize uses to point to their actual clobbering definitions.
1252void MemorySSA::OptimizeUses::optimizeUses() {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001253 SmallVector<MemoryAccess *, 16> VersionStack;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001254 DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001255 VersionStack.push_back(MSSA->getLiveOnEntryDef());
1256
1257 unsigned long StackEpoch = 1;
1258 unsigned long PopEpoch = 1;
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001259 // We perform a non-recursive top-down dominator tree walk.
Daniel Berlin7ac3d742016-08-05 22:09:14 +00001260 for (const auto *DomNode : depth_first(DT->getRootNode()))
1261 optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1262 LocStackInfo);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001263}
1264
Daniel Berlin3d512a22016-08-22 19:14:30 +00001265void MemorySSA::placePHINodes(
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001266 const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks,
1267 const DenseMap<const BasicBlock *, unsigned int> &BBNumbers) {
Daniel Berlin3d512a22016-08-22 19:14:30 +00001268 // Determine where our MemoryPhi's should go
1269 ForwardIDFCalculator IDFs(*DT);
1270 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001271 SmallVector<BasicBlock *, 32> IDFBlocks;
1272 IDFs.calculate(IDFBlocks);
1273
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001274 std::sort(IDFBlocks.begin(), IDFBlocks.end(),
1275 [&BBNumbers](const BasicBlock *A, const BasicBlock *B) {
1276 return BBNumbers.lookup(A) < BBNumbers.lookup(B);
1277 });
1278
Daniel Berlin3d512a22016-08-22 19:14:30 +00001279 // Now place MemoryPhi nodes.
Daniel Berlind602e042017-01-25 20:56:19 +00001280 for (auto &BB : IDFBlocks)
1281 createMemoryPhi(BB);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001282}
1283
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001284void MemorySSA::buildMemorySSA() {
George Burgess IVe1100f52016-02-02 22:46:49 +00001285 // We create an access to represent "live on entry", for things like
1286 // arguments or users of globals, where the memory they use is defined before
1287 // the beginning of the function. We do not actually insert it into the IR.
1288 // We do not define a live on exit for the immediate uses, and thus our
1289 // semantics do *not* imply that something with no immediate uses can simply
1290 // be removed.
1291 BasicBlock &StartingPoint = F.getEntryBlock();
1292 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
1293 &StartingPoint, NextID++);
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001294 DenseMap<const BasicBlock *, unsigned int> BBNumbers;
1295 unsigned NextBBNum = 0;
George Burgess IVe1100f52016-02-02 22:46:49 +00001296
1297 // We maintain lists of memory accesses per-block, trading memory for time. We
1298 // could just look up the memory access for every possible instruction in the
1299 // stream.
1300 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001301 SmallPtrSet<BasicBlock *, 32> DefUseBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001302 // Go through each block, figure out where defs occur, and chain together all
1303 // the accesses.
1304 for (BasicBlock &B : F) {
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001305 BBNumbers[&B] = NextBBNum++;
Daniel Berlin7898ca62016-02-07 01:52:15 +00001306 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001307 AccessList *Accesses = nullptr;
Daniel Berlind602e042017-01-25 20:56:19 +00001308 DefsList *Defs = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001309 for (Instruction &I : B) {
Peter Collingbourneffecb142016-05-26 01:19:17 +00001310 MemoryUseOrDef *MUD = createNewAccess(&I);
George Burgess IVb42b7622016-03-11 19:34:03 +00001311 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001312 continue;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001313
George Burgess IVe1100f52016-02-02 22:46:49 +00001314 if (!Accesses)
1315 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001316 Accesses->push_back(MUD);
Daniel Berlind602e042017-01-25 20:56:19 +00001317 if (isa<MemoryDef>(MUD)) {
1318 InsertIntoDef = true;
1319 if (!Defs)
1320 Defs = getOrCreateDefsList(&B);
1321 Defs->push_back(*MUD);
1322 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001323 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001324 if (InsertIntoDef)
1325 DefiningBlocks.insert(&B);
George Burgess IV3887a412016-03-21 21:25:39 +00001326 if (Accesses)
Daniel Berlin1b51a292016-02-07 01:52:19 +00001327 DefUseBlocks.insert(&B);
1328 }
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001329 placePHINodes(DefiningBlocks, BBNumbers);
George Burgess IVe1100f52016-02-02 22:46:49 +00001330
1331 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1332 // filled in with all blocks.
1333 SmallPtrSet<BasicBlock *, 16> Visited;
1334 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1335
George Burgess IV5f308972016-07-19 01:29:15 +00001336 CachingWalker *Walker = getWalkerImpl();
1337
1338 // We're doing a batch of updates; don't drop useful caches between them.
1339 Walker->setAutoResetWalker(false);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001340 OptimizeUses(this, Walker, AA, DT).optimizeUses();
George Burgess IV5f308972016-07-19 01:29:15 +00001341 Walker->setAutoResetWalker(true);
1342 Walker->resetClobberWalker();
1343
George Burgess IVe1100f52016-02-02 22:46:49 +00001344 // Mark the uses in unreachable blocks as live on entry, so that they go
1345 // somewhere.
1346 for (auto &BB : F)
1347 if (!Visited.count(&BB))
1348 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001349}
George Burgess IVe1100f52016-02-02 22:46:49 +00001350
George Burgess IV5f308972016-07-19 01:29:15 +00001351MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1352
1353MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001354 if (Walker)
1355 return Walker.get();
1356
1357 Walker = make_unique<CachingWalker>(this, AA, DT);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001358 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001359}
1360
Daniel Berlind602e042017-01-25 20:56:19 +00001361// This is a helper function used by the creation routines. It places NewAccess
1362// into the access and defs lists for a given basic block, at the given
1363// insertion point.
1364void MemorySSA::insertIntoListsForBlock(MemoryAccess *NewAccess,
1365 const BasicBlock *BB,
1366 InsertionPlace Point) {
1367 auto *Accesses = getOrCreateAccessList(BB);
1368 if (Point == Beginning) {
1369 // If it's a phi node, it goes first, otherwise, it goes after any phi
1370 // nodes.
1371 if (isa<MemoryPhi>(NewAccess)) {
1372 Accesses->push_front(NewAccess);
1373 auto *Defs = getOrCreateDefsList(BB);
1374 Defs->push_front(*NewAccess);
1375 } else {
1376 auto AI = find_if_not(
1377 *Accesses, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1378 Accesses->insert(AI, NewAccess);
1379 if (!isa<MemoryUse>(NewAccess)) {
1380 auto *Defs = getOrCreateDefsList(BB);
1381 auto DI = find_if_not(
1382 *Defs, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1383 Defs->insert(DI, *NewAccess);
1384 }
1385 }
1386 } else {
1387 Accesses->push_back(NewAccess);
1388 if (!isa<MemoryUse>(NewAccess)) {
1389 auto *Defs = getOrCreateDefsList(BB);
1390 Defs->push_back(*NewAccess);
1391 }
1392 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001393 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001394}
1395
1396void MemorySSA::insertIntoListsBefore(MemoryAccess *What, const BasicBlock *BB,
1397 AccessList::iterator InsertPt) {
1398 auto *Accesses = getWritableBlockAccesses(BB);
1399 bool WasEnd = InsertPt == Accesses->end();
1400 Accesses->insert(AccessList::iterator(InsertPt), What);
1401 if (!isa<MemoryUse>(What)) {
1402 auto *Defs = getOrCreateDefsList(BB);
1403 // If we got asked to insert at the end, we have an easy job, just shove it
1404 // at the end. If we got asked to insert before an existing def, we also get
1405 // an terator. If we got asked to insert before a use, we have to hunt for
1406 // the next def.
1407 if (WasEnd) {
1408 Defs->push_back(*What);
1409 } else if (isa<MemoryDef>(InsertPt)) {
1410 Defs->insert(InsertPt->getDefsIterator(), *What);
1411 } else {
1412 while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt))
1413 ++InsertPt;
1414 // Either we found a def, or we are inserting at the end
1415 if (InsertPt == Accesses->end())
1416 Defs->push_back(*What);
1417 else
1418 Defs->insert(InsertPt->getDefsIterator(), *What);
1419 }
1420 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001421 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001422}
1423
Daniel Berlin60ead052017-01-28 01:23:13 +00001424// Move What before Where in the IR. The end result is taht What will belong to
1425// the right lists and have the right Block set, but will not otherwise be
1426// correct. It will not have the right defining access, and if it is a def,
1427// things below it will not properly be updated.
1428void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
1429 AccessList::iterator Where) {
1430 // Keep it in the lookup tables, remove from the lists
1431 removeFromLists(What, false);
1432 What->setBlock(BB);
1433 insertIntoListsBefore(What, BB, Where);
1434}
1435
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001436void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
1437 InsertionPlace Point) {
1438 removeFromLists(What, false);
1439 What->setBlock(BB);
1440 insertIntoListsForBlock(What, BB, Point);
1441}
1442
Daniel Berlin14300262016-06-21 18:39:20 +00001443MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1444 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
Daniel Berlin14300262016-06-21 18:39:20 +00001445 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001446 // Phi's always are placed at the front of the block.
Daniel Berlind602e042017-01-25 20:56:19 +00001447 insertIntoListsForBlock(Phi, BB, Beginning);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001448 ValueToMemoryAccess[BB] = Phi;
Daniel Berlin14300262016-06-21 18:39:20 +00001449 return Phi;
1450}
1451
1452MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
1453 MemoryAccess *Definition) {
1454 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1455 MemoryUseOrDef *NewAccess = createNewAccess(I);
1456 assert(
1457 NewAccess != nullptr &&
1458 "Tried to create a memory access for a non-memory touching instruction");
1459 NewAccess->setDefiningAccess(Definition);
1460 return NewAccess;
1461}
1462
Daniel Berlind952cea2017-04-07 01:28:36 +00001463// Return true if the instruction has ordering constraints.
1464// Note specifically that this only considers stores and loads
1465// because others are still considered ModRef by getModRefInfo.
1466static inline bool isOrdered(const Instruction *I) {
1467 if (auto *SI = dyn_cast<StoreInst>(I)) {
1468 if (!SI->isUnordered())
1469 return true;
1470 } else if (auto *LI = dyn_cast<LoadInst>(I)) {
1471 if (!LI->isUnordered())
1472 return true;
1473 }
1474 return false;
1475}
George Burgess IVe1100f52016-02-02 22:46:49 +00001476/// \brief Helper function to create new memory accesses
Peter Collingbourneffecb142016-05-26 01:19:17 +00001477MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001478 // The assume intrinsic has a control dependency which we model by claiming
1479 // that it writes arbitrarily. Ignore that fake memory dependency here.
1480 // FIXME: Replace this special casing with a more accurate modelling of
1481 // assume's control dependency.
1482 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1483 if (II->getIntrinsicID() == Intrinsic::assume)
1484 return nullptr;
1485
George Burgess IVe1100f52016-02-02 22:46:49 +00001486 // Find out what affect this instruction has on memory.
1487 ModRefInfo ModRef = AA->getModRefInfo(I);
Daniel Berlind952cea2017-04-07 01:28:36 +00001488 // The isOrdered check is used to ensure that volatiles end up as defs
1489 // (atomics end up as ModRef right now anyway). Until we separate the
1490 // ordering chain from the memory chain, this enables people to see at least
1491 // some relative ordering to volatiles. Note that getClobberingMemoryAccess
1492 // will still give an answer that bypasses other volatile loads. TODO:
1493 // Separate memory aliasing and ordering into two different chains so that we
1494 // can precisely represent both "what memory will this read/write/is clobbered
1495 // by" and "what instructions can I move this past".
1496 bool Def = bool(ModRef & MRI_Mod) || isOrdered(I);
George Burgess IVe1100f52016-02-02 22:46:49 +00001497 bool Use = bool(ModRef & MRI_Ref);
1498
1499 // It's possible for an instruction to not modify memory at all. During
1500 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +00001501 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +00001502 return nullptr;
1503
1504 assert((Def || Use) &&
1505 "Trying to create a memory access with a non-memory instruction");
1506
George Burgess IVb42b7622016-03-11 19:34:03 +00001507 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001508 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +00001509 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +00001510 else
George Burgess IVb42b7622016-03-11 19:34:03 +00001511 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
Daniel Berlin5130cc82016-07-31 21:08:20 +00001512 ValueToMemoryAccess[I] = MUD;
George Burgess IVb42b7622016-03-11 19:34:03 +00001513 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001514}
1515
George Burgess IVe1100f52016-02-02 22:46:49 +00001516/// \brief Returns true if \p Replacer dominates \p Replacee .
1517bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1518 const MemoryAccess *Replacee) const {
1519 if (isa<MemoryUseOrDef>(Replacee))
1520 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1521 const auto *MP = cast<MemoryPhi>(Replacee);
1522 // For a phi node, the use occurs in the predecessor block of the phi node.
1523 // Since we may occur multiple times in the phi node, we have to check each
1524 // operand to ensure Replacer dominates each operand where Replacee occurs.
1525 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +00001526 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +00001527 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1528 return false;
1529 }
1530 return true;
1531}
1532
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001533/// \brief Properly remove \p MA from all of MemorySSA's lookup tables.
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001534void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1535 assert(MA->use_empty() &&
1536 "Trying to remove memory access that still has uses");
Daniel Berlin5c46b942016-07-19 22:49:43 +00001537 BlockNumbering.erase(MA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001538 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
1539 MUD->setDefiningAccess(nullptr);
1540 // Invalidate our walker's cache if necessary
1541 if (!isa<MemoryUse>(MA))
1542 Walker->invalidateInfo(MA);
1543 // The call below to erase will destroy MA, so we can't change the order we
1544 // are doing things here
1545 Value *MemoryInst;
1546 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1547 MemoryInst = MUD->getMemoryInst();
1548 } else {
1549 MemoryInst = MA->getBlock();
1550 }
Daniel Berlin5130cc82016-07-31 21:08:20 +00001551 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1552 if (VMA->second == MA)
1553 ValueToMemoryAccess.erase(VMA);
Daniel Berlin60ead052017-01-28 01:23:13 +00001554}
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001555
Daniel Berlin60ead052017-01-28 01:23:13 +00001556/// \brief Properly remove \p MA from all of MemorySSA's lists.
1557///
1558/// Because of the way the intrusive list and use lists work, it is important to
1559/// do removal in the right order.
1560/// ShouldDelete defaults to true, and will cause the memory access to also be
1561/// deleted, not just removed.
1562void MemorySSA::removeFromLists(MemoryAccess *MA, bool ShouldDelete) {
Daniel Berlind602e042017-01-25 20:56:19 +00001563 // The access list owns the reference, so we erase it from the non-owning list
1564 // first.
1565 if (!isa<MemoryUse>(MA)) {
1566 auto DefsIt = PerBlockDefs.find(MA->getBlock());
1567 std::unique_ptr<DefsList> &Defs = DefsIt->second;
1568 Defs->remove(*MA);
1569 if (Defs->empty())
1570 PerBlockDefs.erase(DefsIt);
1571 }
1572
Daniel Berlin60ead052017-01-28 01:23:13 +00001573 // The erase call here will delete it. If we don't want it deleted, we call
1574 // remove instead.
George Burgess IVe0e6e482016-03-02 02:35:04 +00001575 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
Daniel Berlinada263d2016-06-20 20:21:33 +00001576 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin60ead052017-01-28 01:23:13 +00001577 if (ShouldDelete)
1578 Accesses->erase(MA);
1579 else
1580 Accesses->remove(MA);
1581
George Burgess IVe0e6e482016-03-02 02:35:04 +00001582 if (Accesses->empty())
1583 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001584}
1585
George Burgess IVe1100f52016-02-02 22:46:49 +00001586void MemorySSA::print(raw_ostream &OS) const {
1587 MemorySSAAnnotatedWriter Writer(this);
1588 F.print(OS, &Writer);
1589}
1590
Matthias Braun8c209aa2017-01-28 02:02:38 +00001591#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Daniel Berlin78cbd282017-02-20 22:26:03 +00001592LLVM_DUMP_METHOD void MemorySSA::dump() const { print(dbgs()); }
Matthias Braun8c209aa2017-01-28 02:02:38 +00001593#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001594
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001595void MemorySSA::verifyMemorySSA() const {
1596 verifyDefUses(F);
1597 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001598 verifyOrdering(F);
Geoff Berrycdf53332016-08-08 17:52:01 +00001599 Walker->verify(this);
Daniel Berlin14300262016-06-21 18:39:20 +00001600}
1601
1602/// \brief Verify that the order and existence of MemoryAccesses matches the
1603/// order and existence of memory affecting instructions.
1604void MemorySSA::verifyOrdering(Function &F) const {
1605 // Walk all the blocks, comparing what the lookups think and what the access
1606 // lists think, as well as the order in the blocks vs the order in the access
1607 // lists.
1608 SmallVector<MemoryAccess *, 32> ActualAccesses;
Daniel Berlind602e042017-01-25 20:56:19 +00001609 SmallVector<MemoryAccess *, 32> ActualDefs;
Daniel Berlin14300262016-06-21 18:39:20 +00001610 for (BasicBlock &B : F) {
1611 const AccessList *AL = getBlockAccesses(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001612 const auto *DL = getBlockDefs(&B);
Daniel Berlin14300262016-06-21 18:39:20 +00001613 MemoryAccess *Phi = getMemoryAccess(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001614 if (Phi) {
Daniel Berlin14300262016-06-21 18:39:20 +00001615 ActualAccesses.push_back(Phi);
Daniel Berlind602e042017-01-25 20:56:19 +00001616 ActualDefs.push_back(Phi);
1617 }
1618
Daniel Berlin14300262016-06-21 18:39:20 +00001619 for (Instruction &I : B) {
1620 MemoryAccess *MA = getMemoryAccess(&I);
Daniel Berlind602e042017-01-25 20:56:19 +00001621 assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) &&
1622 "We have memory affecting instructions "
1623 "in this block but they are not in the "
1624 "access list or defs list");
1625 if (MA) {
Daniel Berlin14300262016-06-21 18:39:20 +00001626 ActualAccesses.push_back(MA);
Daniel Berlind602e042017-01-25 20:56:19 +00001627 if (isa<MemoryDef>(MA))
1628 ActualDefs.push_back(MA);
1629 }
Daniel Berlin14300262016-06-21 18:39:20 +00001630 }
1631 // Either we hit the assert, really have no accesses, or we have both
Daniel Berlind602e042017-01-25 20:56:19 +00001632 // accesses and an access list.
1633 // Same with defs.
1634 if (!AL && !DL)
Daniel Berlin14300262016-06-21 18:39:20 +00001635 continue;
1636 assert(AL->size() == ActualAccesses.size() &&
1637 "We don't have the same number of accesses in the block as on the "
1638 "access list");
Davide Italiano6c77de02017-01-30 03:16:43 +00001639 assert((DL || ActualDefs.size() == 0) &&
1640 "Either we should have a defs list, or we should have no defs");
Daniel Berlind602e042017-01-25 20:56:19 +00001641 assert((!DL || DL->size() == ActualDefs.size()) &&
1642 "We don't have the same number of defs in the block as on the "
1643 "def list");
Daniel Berlin14300262016-06-21 18:39:20 +00001644 auto ALI = AL->begin();
1645 auto AAI = ActualAccesses.begin();
1646 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1647 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1648 ++ALI;
1649 ++AAI;
1650 }
1651 ActualAccesses.clear();
Daniel Berlind602e042017-01-25 20:56:19 +00001652 if (DL) {
1653 auto DLI = DL->begin();
1654 auto ADI = ActualDefs.begin();
1655 while (DLI != DL->end() && ADI != ActualDefs.end()) {
1656 assert(&*DLI == *ADI && "Not the same defs in the same order");
1657 ++DLI;
1658 ++ADI;
1659 }
1660 }
1661 ActualDefs.clear();
Daniel Berlin14300262016-06-21 18:39:20 +00001662 }
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001663}
1664
George Burgess IVe1100f52016-02-02 22:46:49 +00001665/// \brief Verify the domination properties of MemorySSA by checking that each
1666/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001667void MemorySSA::verifyDomination(Function &F) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001668#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001669 for (BasicBlock &B : F) {
1670 // Phi nodes are attached to basic blocks
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001671 if (MemoryPhi *MP = getMemoryAccess(&B))
1672 for (const Use &U : MP->uses())
1673 assert(dominates(MP, U) && "Memory PHI does not dominate it's uses");
Daniel Berlin7af95872016-08-05 21:47:20 +00001674
George Burgess IVe1100f52016-02-02 22:46:49 +00001675 for (Instruction &I : B) {
1676 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
1677 if (!MD)
1678 continue;
1679
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001680 for (const Use &U : MD->uses())
1681 assert(dominates(MD, U) && "Memory Def does not dominate it's uses");
George Burgess IVe1100f52016-02-02 22:46:49 +00001682 }
1683 }
Daniel Berlin7af95872016-08-05 21:47:20 +00001684#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001685}
1686
1687/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
1688/// appears in the use list of \p Def.
Daniel Berlin7af95872016-08-05 21:47:20 +00001689
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001690void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001691#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001692 // The live on entry use may cause us to get a NULL def here
Daniel Berlin7af95872016-08-05 21:47:20 +00001693 if (!Def)
1694 assert(isLiveOnEntryDef(Use) &&
1695 "Null def but use not point to live on entry def");
1696 else
Daniel Berlinda2f38e2016-08-11 21:26:50 +00001697 assert(is_contained(Def->users(), Use) &&
Daniel Berlin7af95872016-08-05 21:47:20 +00001698 "Did not find use in def's use list");
1699#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001700}
1701
1702/// \brief Verify the immediate use information, by walking all the memory
1703/// accesses and verifying that, for each use, it appears in the
1704/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001705void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001706 for (BasicBlock &B : F) {
1707 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00001708 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00001709 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
1710 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00001711 "Incomplete MemoryPhi Node");
George Burgess IVe1100f52016-02-02 22:46:49 +00001712 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1713 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Daniel Berlin14300262016-06-21 18:39:20 +00001714 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001715
1716 for (Instruction &I : B) {
George Burgess IV66837ab2016-11-01 21:17:46 +00001717 if (MemoryUseOrDef *MA = getMemoryAccess(&I)) {
1718 verifyUseInDefs(MA->getDefiningAccess(), MA);
George Burgess IVe1100f52016-02-02 22:46:49 +00001719 }
1720 }
1721 }
1722}
1723
George Burgess IV66837ab2016-11-01 21:17:46 +00001724MemoryUseOrDef *MemorySSA::getMemoryAccess(const Instruction *I) const {
1725 return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I));
George Burgess IVe1100f52016-02-02 22:46:49 +00001726}
1727
1728MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
George Burgess IV66837ab2016-11-01 21:17:46 +00001729 return cast_or_null<MemoryPhi>(ValueToMemoryAccess.lookup(cast<Value>(BB)));
George Burgess IVe1100f52016-02-02 22:46:49 +00001730}
1731
Daniel Berlin5c46b942016-07-19 22:49:43 +00001732/// Perform a local numbering on blocks so that instruction ordering can be
1733/// determined in constant time.
1734/// TODO: We currently just number in order. If we numbered by N, we could
1735/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
1736/// log2(N) sequences of mixed before and after) without needing to invalidate
1737/// the numbering.
1738void MemorySSA::renumberBlock(const BasicBlock *B) const {
1739 // The pre-increment ensures the numbers really start at 1.
1740 unsigned long CurrentNumber = 0;
1741 const AccessList *AL = getBlockAccesses(B);
1742 assert(AL != nullptr && "Asking to renumber an empty block");
1743 for (const auto &I : *AL)
1744 BlockNumbering[&I] = ++CurrentNumber;
1745 BlockNumberingValid.insert(B);
1746}
1747
George Burgess IVe1100f52016-02-02 22:46:49 +00001748/// \brief Determine, for two memory accesses in the same block,
1749/// whether \p Dominator dominates \p Dominatee.
1750/// \returns True if \p Dominator dominates \p Dominatee.
1751bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
1752 const MemoryAccess *Dominatee) const {
Sebastian Pope1f60b12016-06-10 21:36:41 +00001753
Daniel Berlin5c46b942016-07-19 22:49:43 +00001754 const BasicBlock *DominatorBlock = Dominator->getBlock();
Daniel Berlin5c46b942016-07-19 22:49:43 +00001755
Daniel Berlin19860302016-07-19 23:08:08 +00001756 assert((DominatorBlock == Dominatee->getBlock()) &&
Daniel Berlin5c46b942016-07-19 22:49:43 +00001757 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00001758 // A node dominates itself.
1759 if (Dominatee == Dominator)
1760 return true;
1761
1762 // When Dominatee is defined on function entry, it is not dominated by another
1763 // memory access.
1764 if (isLiveOnEntryDef(Dominatee))
1765 return false;
1766
1767 // When Dominator is defined on function entry, it dominates the other memory
1768 // access.
1769 if (isLiveOnEntryDef(Dominator))
1770 return true;
1771
Daniel Berlin5c46b942016-07-19 22:49:43 +00001772 if (!BlockNumberingValid.count(DominatorBlock))
1773 renumberBlock(DominatorBlock);
George Burgess IVe1100f52016-02-02 22:46:49 +00001774
Daniel Berlin5c46b942016-07-19 22:49:43 +00001775 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
1776 // All numbers start with 1
1777 assert(DominatorNum != 0 && "Block was not numbered properly");
1778 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
1779 assert(DominateeNum != 0 && "Block was not numbered properly");
1780 return DominatorNum < DominateeNum;
George Burgess IVe1100f52016-02-02 22:46:49 +00001781}
1782
George Burgess IV5f308972016-07-19 01:29:15 +00001783bool MemorySSA::dominates(const MemoryAccess *Dominator,
1784 const MemoryAccess *Dominatee) const {
1785 if (Dominator == Dominatee)
1786 return true;
1787
1788 if (isLiveOnEntryDef(Dominatee))
1789 return false;
1790
1791 if (Dominator->getBlock() != Dominatee->getBlock())
1792 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
1793 return locallyDominates(Dominator, Dominatee);
1794}
1795
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001796bool MemorySSA::dominates(const MemoryAccess *Dominator,
1797 const Use &Dominatee) const {
1798 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
1799 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
1800 // The def must dominate the incoming block of the phi.
1801 if (UseBB != Dominator->getBlock())
1802 return DT->dominates(Dominator->getBlock(), UseBB);
1803 // If the UseBB and the DefBB are the same, compare locally.
1804 return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
1805 }
1806 // If it's not a PHI node use, the normal dominates can already handle it.
1807 return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
1808}
1809
George Burgess IVe1100f52016-02-02 22:46:49 +00001810const static char LiveOnEntryStr[] = "liveOnEntry";
1811
1812void MemoryDef::print(raw_ostream &OS) const {
1813 MemoryAccess *UO = getDefiningAccess();
1814
1815 OS << getID() << " = MemoryDef(";
1816 if (UO && UO->getID())
1817 OS << UO->getID();
1818 else
1819 OS << LiveOnEntryStr;
1820 OS << ')';
1821}
1822
1823void MemoryPhi::print(raw_ostream &OS) const {
1824 bool First = true;
1825 OS << getID() << " = MemoryPhi(";
1826 for (const auto &Op : operands()) {
1827 BasicBlock *BB = getIncomingBlock(Op);
1828 MemoryAccess *MA = cast<MemoryAccess>(Op);
1829 if (!First)
1830 OS << ',';
1831 else
1832 First = false;
1833
1834 OS << '{';
1835 if (BB->hasName())
1836 OS << BB->getName();
1837 else
1838 BB->printAsOperand(OS, false);
1839 OS << ',';
1840 if (unsigned ID = MA->getID())
1841 OS << ID;
1842 else
1843 OS << LiveOnEntryStr;
1844 OS << '}';
1845 }
1846 OS << ')';
1847}
1848
1849MemoryAccess::~MemoryAccess() {}
1850
1851void MemoryUse::print(raw_ostream &OS) const {
1852 MemoryAccess *UO = getDefiningAccess();
1853 OS << "MemoryUse(";
1854 if (UO && UO->getID())
1855 OS << UO->getID();
1856 else
1857 OS << LiveOnEntryStr;
1858 OS << ')';
1859}
1860
1861void MemoryAccess::dump() const {
Daniel Berlin78cbd282017-02-20 22:26:03 +00001862// Cannot completely remove virtual function even in release mode.
Matthias Braun8c209aa2017-01-28 02:02:38 +00001863#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
George Burgess IVe1100f52016-02-02 22:46:49 +00001864 print(dbgs());
1865 dbgs() << "\n";
Matthias Braun8c209aa2017-01-28 02:02:38 +00001866#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001867}
1868
Chad Rosier232e29e2016-07-06 21:20:47 +00001869char MemorySSAPrinterLegacyPass::ID = 0;
1870
1871MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
1872 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
1873}
1874
1875void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
1876 AU.setPreservesAll();
1877 AU.addRequired<MemorySSAWrapperPass>();
1878 AU.addPreserved<MemorySSAWrapperPass>();
1879}
1880
1881bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
1882 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
1883 MSSA.print(dbgs());
1884 if (VerifyMemorySSA)
1885 MSSA.verifyMemorySSA();
1886 return false;
1887}
1888
Chandler Carruthdab4eae2016-11-23 17:53:26 +00001889AnalysisKey MemorySSAAnalysis::Key;
George Burgess IVe1100f52016-02-02 22:46:49 +00001890
Daniel Berlin1e98c042016-09-26 17:22:54 +00001891MemorySSAAnalysis::Result MemorySSAAnalysis::run(Function &F,
1892 FunctionAnalysisManager &AM) {
Geoff Berryb96d3b22016-06-01 21:30:40 +00001893 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1894 auto &AA = AM.getResult<AAManager>(F);
Geoff Berry290a13e2016-08-08 18:27:22 +00001895 return MemorySSAAnalysis::Result(make_unique<MemorySSA>(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00001896}
1897
Geoff Berryb96d3b22016-06-01 21:30:40 +00001898PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
1899 FunctionAnalysisManager &AM) {
1900 OS << "MemorySSA for function: " << F.getName() << "\n";
Geoff Berry290a13e2016-08-08 18:27:22 +00001901 AM.getResult<MemorySSAAnalysis>(F).getMSSA().print(OS);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001902
1903 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00001904}
1905
Geoff Berryb96d3b22016-06-01 21:30:40 +00001906PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
1907 FunctionAnalysisManager &AM) {
Geoff Berry290a13e2016-08-08 18:27:22 +00001908 AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001909
1910 return PreservedAnalyses::all();
1911}
1912
1913char MemorySSAWrapperPass::ID = 0;
1914
1915MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
1916 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
1917}
1918
1919void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
1920
1921void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001922 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001923 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
1924 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001925}
1926
Geoff Berryb96d3b22016-06-01 21:30:40 +00001927bool MemorySSAWrapperPass::runOnFunction(Function &F) {
1928 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1929 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1930 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00001931 return false;
1932}
1933
Geoff Berryb96d3b22016-06-01 21:30:40 +00001934void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00001935
Geoff Berryb96d3b22016-06-01 21:30:40 +00001936void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001937 MSSA->print(OS);
1938}
1939
George Burgess IVe1100f52016-02-02 22:46:49 +00001940MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
1941
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001942MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A,
1943 DominatorTree *D)
Daniel Berlind7a7ae02017-04-05 19:01:58 +00001944 : MemorySSAWalker(M), Walker(*M, *A, *D), AutoResetWalker(true) {}
George Burgess IVe1100f52016-02-02 22:46:49 +00001945
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001946MemorySSA::CachingWalker::~CachingWalker() {}
George Burgess IVe1100f52016-02-02 22:46:49 +00001947
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001948void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) {
Daniel Berlind7a7ae02017-04-05 19:01:58 +00001949 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1950 MUD->resetOptimized();
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001951}
1952
George Burgess IVe1100f52016-02-02 22:46:49 +00001953/// \brief Walk the use-def chains starting at \p MA and find
1954/// the MemoryAccess that actually clobbers Loc.
1955///
1956/// \returns our clobbering memory access
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001957MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
1958 MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +00001959 MemoryAccess *New = Walker.findClobber(StartingAccess, Q);
1960#ifdef EXPENSIVE_CHECKS
Daniel Berlind7a7ae02017-04-05 19:01:58 +00001961 MemoryAccess *NewNoCache = Walker.findClobber(StartingAccess, Q);
George Burgess IV5f308972016-07-19 01:29:15 +00001962 assert(NewNoCache == New && "Cache made us hand back a different result?");
1963#endif
1964 if (AutoResetWalker)
1965 resetClobberWalker();
1966 return New;
George Burgess IVe1100f52016-02-02 22:46:49 +00001967}
1968
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001969MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
George Burgess IV013fd732016-10-28 19:22:46 +00001970 MemoryAccess *StartingAccess, const MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001971 if (isa<MemoryPhi>(StartingAccess))
1972 return StartingAccess;
1973
1974 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
1975 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
1976 return StartingUseOrDef;
1977
1978 Instruction *I = StartingUseOrDef->getMemoryInst();
1979
1980 // Conservatively, fences are always clobbers, so don't perform the walk if we
1981 // hit a fence.
David Majnemera940f362016-07-15 17:19:24 +00001982 if (!ImmutableCallSite(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00001983 return StartingUseOrDef;
1984
1985 UpwardsMemoryQuery Q;
1986 Q.OriginalAccess = StartingUseOrDef;
1987 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00001988 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00001989 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00001990
George Burgess IVe1100f52016-02-02 22:46:49 +00001991 // Unlike the other function, do not walk to the def of a def, because we are
1992 // handed something we already believe is the clobbering access.
1993 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
1994 ? StartingUseOrDef->getDefiningAccess()
1995 : StartingUseOrDef;
1996
1997 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00001998 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
1999 DEBUG(dbgs() << *StartingUseOrDef << "\n");
2000 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2001 DEBUG(dbgs() << *Clobber << "\n");
2002 return Clobber;
2003}
2004
2005MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002006MemorySSA::CachingWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
2007 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2008 // If this is a MemoryPhi, we can't do anything.
2009 if (!StartingAccess)
2010 return MA;
George Burgess IVe1100f52016-02-02 22:46:49 +00002011
Daniel Berlincd2deac2016-10-20 20:13:45 +00002012 // If this is an already optimized use or def, return the optimized result.
2013 // Note: Currently, we do not store the optimized def result because we'd need
2014 // a separate field, since we can't use it as the defining access.
Daniel Berline33bc312017-04-04 23:43:10 +00002015 if (auto *MUD = dyn_cast<MemoryUseOrDef>(StartingAccess))
2016 if (MUD->isOptimized())
2017 return MUD->getOptimized();
Daniel Berlincd2deac2016-10-20 20:13:45 +00002018
George Burgess IV400ae402016-07-20 19:51:34 +00002019 const Instruction *I = StartingAccess->getMemoryInst();
George Burgess IV5f308972016-07-19 01:29:15 +00002020 UpwardsMemoryQuery Q(I, StartingAccess);
David Majnemera940f362016-07-15 17:19:24 +00002021 // We can't sanely do anything with a fences, they conservatively
George Burgess IVe1100f52016-02-02 22:46:49 +00002022 // clobber all memory, and have no locations to get pointers from to
David Majnemera940f362016-07-15 17:19:24 +00002023 // try to disambiguate.
George Burgess IV5f308972016-07-19 01:29:15 +00002024 if (!Q.IsCall && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002025 return StartingAccess;
2026
George Burgess IV024f3d22016-08-03 19:57:02 +00002027 if (isUseTriviallyOptimizableToLiveOnEntry(*MSSA->AA, I)) {
2028 MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
Daniel Berline33bc312017-04-04 23:43:10 +00002029 if (auto *MUD = dyn_cast<MemoryUseOrDef>(StartingAccess))
2030 MUD->setOptimized(LiveOnEntry);
George Burgess IV024f3d22016-08-03 19:57:02 +00002031 return LiveOnEntry;
2032 }
2033
George Burgess IVe1100f52016-02-02 22:46:49 +00002034 // Start with the thing we already think clobbers this location
2035 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2036
2037 // At this point, DefiningAccess may be the live on entry def.
2038 // If it is, we will not get a better result.
2039 if (MSSA->isLiveOnEntryDef(DefiningAccess))
2040 return DefiningAccess;
2041
2042 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002043 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2044 DEBUG(dbgs() << *DefiningAccess << "\n");
2045 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2046 DEBUG(dbgs() << *Result << "\n");
Daniel Berline33bc312017-04-04 23:43:10 +00002047 if (auto *MUD = dyn_cast<MemoryUseOrDef>(StartingAccess))
2048 MUD->setOptimized(Result);
George Burgess IVe1100f52016-02-02 22:46:49 +00002049
2050 return Result;
2051}
2052
George Burgess IVe1100f52016-02-02 22:46:49 +00002053MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002054DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002055 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2056 return Use->getDefiningAccess();
2057 return MA;
2058}
2059
2060MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
George Burgess IV013fd732016-10-28 19:22:46 +00002061 MemoryAccess *StartingAccess, const MemoryLocation &) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002062 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2063 return Use->getDefiningAccess();
2064 return StartingAccess;
2065}
George Burgess IV5f308972016-07-19 01:29:15 +00002066} // namespace llvm