blob: 910170561abf6cc5d72eea27a124bc16b6f4d7f3 [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 Berlin554dcd82017-04-11 20:06:36 +000013#include "llvm/Analysis/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
George Burgess IVa362b092016-07-06 00:28:43 +0000979/// \brief This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +0000980/// unreachable blocks, and marking all other unreachable MemoryAccess's as
981/// being uses of the live on entry definition.
982void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
983 assert(!DT->isReachableFromEntry(BB) &&
984 "Reachable block found while handling unreachable blocks");
985
Daniel Berlinfc7e6512016-07-06 05:32:05 +0000986 // Make sure phi nodes in our reachable successors end up with a
987 // LiveOnEntryDef for our incoming edge, even though our block is forward
988 // unreachable. We could just disconnect these blocks from the CFG fully,
989 // but we do not right now.
990 for (const BasicBlock *S : successors(BB)) {
991 if (!DT->isReachableFromEntry(S))
992 continue;
993 auto It = PerBlockAccesses.find(S);
994 // Rename the phi nodes in our successor block
995 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
996 continue;
997 AccessList *Accesses = It->second.get();
998 auto *Phi = cast<MemoryPhi>(&Accesses->front());
999 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1000 }
1001
George Burgess IVe1100f52016-02-02 22:46:49 +00001002 auto It = PerBlockAccesses.find(BB);
1003 if (It == PerBlockAccesses.end())
1004 return;
1005
1006 auto &Accesses = It->second;
1007 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1008 auto Next = std::next(AI);
1009 // If we have a phi, just remove it. We are going to replace all
1010 // users with live on entry.
1011 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1012 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1013 else
1014 Accesses->erase(AI);
1015 AI = Next;
1016 }
1017}
1018
Geoff Berryb96d3b22016-06-01 21:30:40 +00001019MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
1020 : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
Daniel Berlincd2deac2016-10-20 20:13:45 +00001021 NextID(INVALID_MEMORYACCESS_ID) {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001022 buildMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001023}
1024
George Burgess IVe1100f52016-02-02 22:46:49 +00001025MemorySSA::~MemorySSA() {
1026 // Drop all our references
1027 for (const auto &Pair : PerBlockAccesses)
1028 for (MemoryAccess &MA : *Pair.second)
1029 MA.dropAllReferences();
1030}
1031
Daniel Berlin14300262016-06-21 18:39:20 +00001032MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001033 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1034
1035 if (Res.second)
Daniel Berlinada263d2016-06-20 20:21:33 +00001036 Res.first->second = make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001037 return Res.first->second.get();
1038}
Daniel Berlind602e042017-01-25 20:56:19 +00001039MemorySSA::DefsList *MemorySSA::getOrCreateDefsList(const BasicBlock *BB) {
1040 auto Res = PerBlockDefs.insert(std::make_pair(BB, nullptr));
1041
1042 if (Res.second)
1043 Res.first->second = make_unique<DefsList>();
1044 return Res.first->second.get();
1045}
George Burgess IVe1100f52016-02-02 22:46:49 +00001046
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001047/// This class is a batch walker of all MemoryUse's in the program, and points
1048/// their defining access at the thing that actually clobbers them. Because it
1049/// is a batch walker that touches everything, it does not operate like the
1050/// other walkers. This walker is basically performing a top-down SSA renaming
1051/// pass, where the version stack is used as the cache. This enables it to be
1052/// significantly more time and memory efficient than using the regular walker,
1053/// which is walking bottom-up.
1054class MemorySSA::OptimizeUses {
1055public:
1056 OptimizeUses(MemorySSA *MSSA, MemorySSAWalker *Walker, AliasAnalysis *AA,
1057 DominatorTree *DT)
1058 : MSSA(MSSA), Walker(Walker), AA(AA), DT(DT) {
1059 Walker = MSSA->getWalker();
1060 }
1061
1062 void optimizeUses();
1063
1064private:
1065 /// This represents where a given memorylocation is in the stack.
1066 struct MemlocStackInfo {
1067 // This essentially is keeping track of versions of the stack. Whenever
1068 // the stack changes due to pushes or pops, these versions increase.
1069 unsigned long StackEpoch;
1070 unsigned long PopEpoch;
1071 // This is the lower bound of places on the stack to check. It is equal to
1072 // the place the last stack walk ended.
1073 // Note: Correctness depends on this being initialized to 0, which densemap
1074 // does
1075 unsigned long LowerBound;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001076 const BasicBlock *LowerBoundBlock;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001077 // This is where the last walk for this memory location ended.
1078 unsigned long LastKill;
1079 bool LastKillValid;
1080 };
1081 void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1082 SmallVectorImpl<MemoryAccess *> &,
1083 DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
1084 MemorySSA *MSSA;
1085 MemorySSAWalker *Walker;
1086 AliasAnalysis *AA;
1087 DominatorTree *DT;
1088};
1089
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001090/// Optimize the uses in a given block This is basically the SSA renaming
1091/// algorithm, with one caveat: We are able to use a single stack for all
1092/// MemoryUses. This is because the set of *possible* reaching MemoryDefs is
1093/// the same for every MemoryUse. The *actual* clobbering MemoryDef is just
1094/// going to be some position in that stack of possible ones.
1095///
1096/// We track the stack positions that each MemoryLocation needs
1097/// to check, and last ended at. This is because we only want to check the
1098/// things that changed since last time. The same MemoryLocation should
1099/// get clobbered by the same store (getModRefInfo does not use invariantness or
1100/// things like this, and if they start, we can modify MemoryLocOrCall to
1101/// include relevant data)
1102void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1103 const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1104 SmallVectorImpl<MemoryAccess *> &VersionStack,
1105 DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
1106
1107 /// If no accesses, nothing to do.
1108 MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
1109 if (Accesses == nullptr)
1110 return;
1111
1112 // Pop everything that doesn't dominate the current block off the stack,
1113 // increment the PopEpoch to account for this.
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001114 while (true) {
1115 assert(
1116 !VersionStack.empty() &&
1117 "Version stack should have liveOnEntry sentinel dominating everything");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001118 BasicBlock *BackBlock = VersionStack.back()->getBlock();
1119 if (DT->dominates(BackBlock, BB))
1120 break;
1121 while (VersionStack.back()->getBlock() == BackBlock)
1122 VersionStack.pop_back();
1123 ++PopEpoch;
1124 }
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001125
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001126 for (MemoryAccess &MA : *Accesses) {
1127 auto *MU = dyn_cast<MemoryUse>(&MA);
1128 if (!MU) {
1129 VersionStack.push_back(&MA);
1130 ++StackEpoch;
1131 continue;
1132 }
1133
George Burgess IV024f3d22016-08-03 19:57:02 +00001134 if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
Daniel Berlincd2deac2016-10-20 20:13:45 +00001135 MU->setDefiningAccess(MSSA->getLiveOnEntryDef(), true);
George Burgess IV024f3d22016-08-03 19:57:02 +00001136 continue;
1137 }
1138
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001139 MemoryLocOrCall UseMLOC(MU);
1140 auto &LocInfo = LocStackInfo[UseMLOC];
Daniel Berlin26fcea92016-08-02 20:02:21 +00001141 // If the pop epoch changed, it means we've removed stuff from top of
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001142 // stack due to changing blocks. We may have to reset the lower bound or
1143 // last kill info.
1144 if (LocInfo.PopEpoch != PopEpoch) {
1145 LocInfo.PopEpoch = PopEpoch;
1146 LocInfo.StackEpoch = StackEpoch;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001147 // If the lower bound was in something that no longer dominates us, we
1148 // have to reset it.
1149 // We can't simply track stack size, because the stack may have had
1150 // pushes/pops in the meantime.
1151 // XXX: This is non-optimal, but only is slower cases with heavily
1152 // branching dominator trees. To get the optimal number of queries would
1153 // be to make lowerbound and lastkill a per-loc stack, and pop it until
1154 // the top of that stack dominates us. This does not seem worth it ATM.
1155 // A much cheaper optimization would be to always explore the deepest
1156 // branch of the dominator tree first. This will guarantee this resets on
1157 // the smallest set of blocks.
1158 if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
Daniel Berlin1e98c042016-09-26 17:22:54 +00001159 !DT->dominates(LocInfo.LowerBoundBlock, BB)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001160 // Reset the lower bound of things to check.
1161 // TODO: Some day we should be able to reset to last kill, rather than
1162 // 0.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001163 LocInfo.LowerBound = 0;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001164 LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001165 LocInfo.LastKillValid = false;
1166 }
1167 } else if (LocInfo.StackEpoch != StackEpoch) {
1168 // If all that has changed is the StackEpoch, we only have to check the
1169 // new things on the stack, because we've checked everything before. In
1170 // this case, the lower bound of things to check remains the same.
1171 LocInfo.PopEpoch = PopEpoch;
1172 LocInfo.StackEpoch = StackEpoch;
1173 }
1174 if (!LocInfo.LastKillValid) {
1175 LocInfo.LastKill = VersionStack.size() - 1;
1176 LocInfo.LastKillValid = true;
1177 }
1178
1179 // At this point, we should have corrected last kill and LowerBound to be
1180 // in bounds.
1181 assert(LocInfo.LowerBound < VersionStack.size() &&
1182 "Lower bound out of range");
1183 assert(LocInfo.LastKill < VersionStack.size() &&
1184 "Last kill info out of range");
1185 // In any case, the new upper bound is the top of the stack.
1186 unsigned long UpperBound = VersionStack.size() - 1;
1187
1188 if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
Daniel Berlin26fcea92016-08-02 20:02:21 +00001189 DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
1190 << *(MU->getMemoryInst()) << ")"
1191 << " because there are " << UpperBound - LocInfo.LowerBound
1192 << " stores to disambiguate\n");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001193 // Because we did not walk, LastKill is no longer valid, as this may
1194 // have been a kill.
1195 LocInfo.LastKillValid = false;
1196 continue;
1197 }
1198 bool FoundClobberResult = false;
1199 while (UpperBound > LocInfo.LowerBound) {
1200 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1201 // For phis, use the walker, see where we ended up, go there
1202 Instruction *UseInst = MU->getMemoryInst();
1203 MemoryAccess *Result = Walker->getClobberingMemoryAccess(UseInst);
1204 // We are guaranteed to find it or something is wrong
1205 while (VersionStack[UpperBound] != Result) {
1206 assert(UpperBound != 0);
1207 --UpperBound;
1208 }
1209 FoundClobberResult = true;
1210 break;
1211 }
1212
1213 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
Daniel Berlindf101192016-08-03 00:01:46 +00001214 // If the lifetime of the pointer ends at this instruction, it's live on
1215 // entry.
1216 if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1217 // Reset UpperBound to liveOnEntryDef's place in the stack
1218 UpperBound = 0;
1219 FoundClobberResult = true;
1220 break;
1221 }
Daniel Berlindff31de2016-08-02 21:57:52 +00001222 if (instructionClobbersQuery(MD, MU, UseMLOC, *AA)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001223 FoundClobberResult = true;
1224 break;
1225 }
1226 --UpperBound;
1227 }
1228 // At the end of this loop, UpperBound is either a clobber, or lower bound
1229 // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1230 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
Daniel Berlincd2deac2016-10-20 20:13:45 +00001231 MU->setDefiningAccess(VersionStack[UpperBound], true);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001232 // We were last killed now by where we got to
1233 LocInfo.LastKill = UpperBound;
1234 } else {
1235 // Otherwise, we checked all the new ones, and now we know we can get to
1236 // LastKill.
Daniel Berlincd2deac2016-10-20 20:13:45 +00001237 MU->setDefiningAccess(VersionStack[LocInfo.LastKill], true);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001238 }
1239 LocInfo.LowerBound = VersionStack.size() - 1;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001240 LocInfo.LowerBoundBlock = BB;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001241 }
1242}
1243
1244/// Optimize uses to point to their actual clobbering definitions.
1245void MemorySSA::OptimizeUses::optimizeUses() {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001246 SmallVector<MemoryAccess *, 16> VersionStack;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001247 DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001248 VersionStack.push_back(MSSA->getLiveOnEntryDef());
1249
1250 unsigned long StackEpoch = 1;
1251 unsigned long PopEpoch = 1;
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001252 // We perform a non-recursive top-down dominator tree walk.
Daniel Berlin7ac3d742016-08-05 22:09:14 +00001253 for (const auto *DomNode : depth_first(DT->getRootNode()))
1254 optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1255 LocStackInfo);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001256}
1257
Daniel Berlin3d512a22016-08-22 19:14:30 +00001258void MemorySSA::placePHINodes(
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001259 const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks,
1260 const DenseMap<const BasicBlock *, unsigned int> &BBNumbers) {
Daniel Berlin3d512a22016-08-22 19:14:30 +00001261 // Determine where our MemoryPhi's should go
1262 ForwardIDFCalculator IDFs(*DT);
1263 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001264 SmallVector<BasicBlock *, 32> IDFBlocks;
1265 IDFs.calculate(IDFBlocks);
1266
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001267 std::sort(IDFBlocks.begin(), IDFBlocks.end(),
1268 [&BBNumbers](const BasicBlock *A, const BasicBlock *B) {
1269 return BBNumbers.lookup(A) < BBNumbers.lookup(B);
1270 });
1271
Daniel Berlin3d512a22016-08-22 19:14:30 +00001272 // Now place MemoryPhi nodes.
Daniel Berlind602e042017-01-25 20:56:19 +00001273 for (auto &BB : IDFBlocks)
1274 createMemoryPhi(BB);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001275}
1276
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001277void MemorySSA::buildMemorySSA() {
George Burgess IVe1100f52016-02-02 22:46:49 +00001278 // We create an access to represent "live on entry", for things like
1279 // arguments or users of globals, where the memory they use is defined before
1280 // the beginning of the function. We do not actually insert it into the IR.
1281 // We do not define a live on exit for the immediate uses, and thus our
1282 // semantics do *not* imply that something with no immediate uses can simply
1283 // be removed.
1284 BasicBlock &StartingPoint = F.getEntryBlock();
1285 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
1286 &StartingPoint, NextID++);
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001287 DenseMap<const BasicBlock *, unsigned int> BBNumbers;
1288 unsigned NextBBNum = 0;
George Burgess IVe1100f52016-02-02 22:46:49 +00001289
1290 // We maintain lists of memory accesses per-block, trading memory for time. We
1291 // could just look up the memory access for every possible instruction in the
1292 // stream.
1293 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001294 SmallPtrSet<BasicBlock *, 32> DefUseBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001295 // Go through each block, figure out where defs occur, and chain together all
1296 // the accesses.
1297 for (BasicBlock &B : F) {
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001298 BBNumbers[&B] = NextBBNum++;
Daniel Berlin7898ca62016-02-07 01:52:15 +00001299 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001300 AccessList *Accesses = nullptr;
Daniel Berlind602e042017-01-25 20:56:19 +00001301 DefsList *Defs = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001302 for (Instruction &I : B) {
Peter Collingbourneffecb142016-05-26 01:19:17 +00001303 MemoryUseOrDef *MUD = createNewAccess(&I);
George Burgess IVb42b7622016-03-11 19:34:03 +00001304 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001305 continue;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001306
George Burgess IVe1100f52016-02-02 22:46:49 +00001307 if (!Accesses)
1308 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001309 Accesses->push_back(MUD);
Daniel Berlind602e042017-01-25 20:56:19 +00001310 if (isa<MemoryDef>(MUD)) {
1311 InsertIntoDef = true;
1312 if (!Defs)
1313 Defs = getOrCreateDefsList(&B);
1314 Defs->push_back(*MUD);
1315 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001316 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001317 if (InsertIntoDef)
1318 DefiningBlocks.insert(&B);
George Burgess IV3887a412016-03-21 21:25:39 +00001319 if (Accesses)
Daniel Berlin1b51a292016-02-07 01:52:19 +00001320 DefUseBlocks.insert(&B);
1321 }
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001322 placePHINodes(DefiningBlocks, BBNumbers);
George Burgess IVe1100f52016-02-02 22:46:49 +00001323
1324 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1325 // filled in with all blocks.
1326 SmallPtrSet<BasicBlock *, 16> Visited;
1327 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1328
George Burgess IV5f308972016-07-19 01:29:15 +00001329 CachingWalker *Walker = getWalkerImpl();
1330
1331 // We're doing a batch of updates; don't drop useful caches between them.
1332 Walker->setAutoResetWalker(false);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001333 OptimizeUses(this, Walker, AA, DT).optimizeUses();
George Burgess IV5f308972016-07-19 01:29:15 +00001334 Walker->setAutoResetWalker(true);
1335 Walker->resetClobberWalker();
1336
George Burgess IVe1100f52016-02-02 22:46:49 +00001337 // Mark the uses in unreachable blocks as live on entry, so that they go
1338 // somewhere.
1339 for (auto &BB : F)
1340 if (!Visited.count(&BB))
1341 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001342}
George Burgess IVe1100f52016-02-02 22:46:49 +00001343
George Burgess IV5f308972016-07-19 01:29:15 +00001344MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1345
1346MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001347 if (Walker)
1348 return Walker.get();
1349
1350 Walker = make_unique<CachingWalker>(this, AA, DT);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001351 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001352}
1353
Daniel Berlind602e042017-01-25 20:56:19 +00001354// This is a helper function used by the creation routines. It places NewAccess
1355// into the access and defs lists for a given basic block, at the given
1356// insertion point.
1357void MemorySSA::insertIntoListsForBlock(MemoryAccess *NewAccess,
1358 const BasicBlock *BB,
1359 InsertionPlace Point) {
1360 auto *Accesses = getOrCreateAccessList(BB);
1361 if (Point == Beginning) {
1362 // If it's a phi node, it goes first, otherwise, it goes after any phi
1363 // nodes.
1364 if (isa<MemoryPhi>(NewAccess)) {
1365 Accesses->push_front(NewAccess);
1366 auto *Defs = getOrCreateDefsList(BB);
1367 Defs->push_front(*NewAccess);
1368 } else {
1369 auto AI = find_if_not(
1370 *Accesses, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1371 Accesses->insert(AI, NewAccess);
1372 if (!isa<MemoryUse>(NewAccess)) {
1373 auto *Defs = getOrCreateDefsList(BB);
1374 auto DI = find_if_not(
1375 *Defs, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1376 Defs->insert(DI, *NewAccess);
1377 }
1378 }
1379 } else {
1380 Accesses->push_back(NewAccess);
1381 if (!isa<MemoryUse>(NewAccess)) {
1382 auto *Defs = getOrCreateDefsList(BB);
1383 Defs->push_back(*NewAccess);
1384 }
1385 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001386 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001387}
1388
1389void MemorySSA::insertIntoListsBefore(MemoryAccess *What, const BasicBlock *BB,
1390 AccessList::iterator InsertPt) {
1391 auto *Accesses = getWritableBlockAccesses(BB);
1392 bool WasEnd = InsertPt == Accesses->end();
1393 Accesses->insert(AccessList::iterator(InsertPt), What);
1394 if (!isa<MemoryUse>(What)) {
1395 auto *Defs = getOrCreateDefsList(BB);
1396 // If we got asked to insert at the end, we have an easy job, just shove it
1397 // at the end. If we got asked to insert before an existing def, we also get
1398 // an terator. If we got asked to insert before a use, we have to hunt for
1399 // the next def.
1400 if (WasEnd) {
1401 Defs->push_back(*What);
1402 } else if (isa<MemoryDef>(InsertPt)) {
1403 Defs->insert(InsertPt->getDefsIterator(), *What);
1404 } else {
1405 while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt))
1406 ++InsertPt;
1407 // Either we found a def, or we are inserting at the end
1408 if (InsertPt == Accesses->end())
1409 Defs->push_back(*What);
1410 else
1411 Defs->insert(InsertPt->getDefsIterator(), *What);
1412 }
1413 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001414 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001415}
1416
Daniel Berlin60ead052017-01-28 01:23:13 +00001417// Move What before Where in the IR. The end result is taht What will belong to
1418// the right lists and have the right Block set, but will not otherwise be
1419// correct. It will not have the right defining access, and if it is a def,
1420// things below it will not properly be updated.
1421void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
1422 AccessList::iterator Where) {
1423 // Keep it in the lookup tables, remove from the lists
1424 removeFromLists(What, false);
1425 What->setBlock(BB);
1426 insertIntoListsBefore(What, BB, Where);
1427}
1428
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001429void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
1430 InsertionPlace Point) {
1431 removeFromLists(What, false);
1432 What->setBlock(BB);
1433 insertIntoListsForBlock(What, BB, Point);
1434}
1435
Daniel Berlin14300262016-06-21 18:39:20 +00001436MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1437 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
Daniel Berlin14300262016-06-21 18:39:20 +00001438 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001439 // Phi's always are placed at the front of the block.
Daniel Berlind602e042017-01-25 20:56:19 +00001440 insertIntoListsForBlock(Phi, BB, Beginning);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001441 ValueToMemoryAccess[BB] = Phi;
Daniel Berlin14300262016-06-21 18:39:20 +00001442 return Phi;
1443}
1444
1445MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
1446 MemoryAccess *Definition) {
1447 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1448 MemoryUseOrDef *NewAccess = createNewAccess(I);
1449 assert(
1450 NewAccess != nullptr &&
1451 "Tried to create a memory access for a non-memory touching instruction");
1452 NewAccess->setDefiningAccess(Definition);
1453 return NewAccess;
1454}
1455
Daniel Berlind952cea2017-04-07 01:28:36 +00001456// Return true if the instruction has ordering constraints.
1457// Note specifically that this only considers stores and loads
1458// because others are still considered ModRef by getModRefInfo.
1459static inline bool isOrdered(const Instruction *I) {
1460 if (auto *SI = dyn_cast<StoreInst>(I)) {
1461 if (!SI->isUnordered())
1462 return true;
1463 } else if (auto *LI = dyn_cast<LoadInst>(I)) {
1464 if (!LI->isUnordered())
1465 return true;
1466 }
1467 return false;
1468}
George Burgess IVe1100f52016-02-02 22:46:49 +00001469/// \brief Helper function to create new memory accesses
Peter Collingbourneffecb142016-05-26 01:19:17 +00001470MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001471 // The assume intrinsic has a control dependency which we model by claiming
1472 // that it writes arbitrarily. Ignore that fake memory dependency here.
1473 // FIXME: Replace this special casing with a more accurate modelling of
1474 // assume's control dependency.
1475 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1476 if (II->getIntrinsicID() == Intrinsic::assume)
1477 return nullptr;
1478
George Burgess IVe1100f52016-02-02 22:46:49 +00001479 // Find out what affect this instruction has on memory.
1480 ModRefInfo ModRef = AA->getModRefInfo(I);
Daniel Berlind952cea2017-04-07 01:28:36 +00001481 // The isOrdered check is used to ensure that volatiles end up as defs
1482 // (atomics end up as ModRef right now anyway). Until we separate the
1483 // ordering chain from the memory chain, this enables people to see at least
1484 // some relative ordering to volatiles. Note that getClobberingMemoryAccess
1485 // will still give an answer that bypasses other volatile loads. TODO:
1486 // Separate memory aliasing and ordering into two different chains so that we
1487 // can precisely represent both "what memory will this read/write/is clobbered
1488 // by" and "what instructions can I move this past".
1489 bool Def = bool(ModRef & MRI_Mod) || isOrdered(I);
George Burgess IVe1100f52016-02-02 22:46:49 +00001490 bool Use = bool(ModRef & MRI_Ref);
1491
1492 // It's possible for an instruction to not modify memory at all. During
1493 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +00001494 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +00001495 return nullptr;
1496
1497 assert((Def || Use) &&
1498 "Trying to create a memory access with a non-memory instruction");
1499
George Burgess IVb42b7622016-03-11 19:34:03 +00001500 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001501 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +00001502 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +00001503 else
George Burgess IVb42b7622016-03-11 19:34:03 +00001504 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
Daniel Berlin5130cc82016-07-31 21:08:20 +00001505 ValueToMemoryAccess[I] = MUD;
George Burgess IVb42b7622016-03-11 19:34:03 +00001506 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001507}
1508
George Burgess IVe1100f52016-02-02 22:46:49 +00001509/// \brief Returns true if \p Replacer dominates \p Replacee .
1510bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1511 const MemoryAccess *Replacee) const {
1512 if (isa<MemoryUseOrDef>(Replacee))
1513 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1514 const auto *MP = cast<MemoryPhi>(Replacee);
1515 // For a phi node, the use occurs in the predecessor block of the phi node.
1516 // Since we may occur multiple times in the phi node, we have to check each
1517 // operand to ensure Replacer dominates each operand where Replacee occurs.
1518 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +00001519 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +00001520 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1521 return false;
1522 }
1523 return true;
1524}
1525
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001526/// \brief Properly remove \p MA from all of MemorySSA's lookup tables.
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001527void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1528 assert(MA->use_empty() &&
1529 "Trying to remove memory access that still has uses");
Daniel Berlin5c46b942016-07-19 22:49:43 +00001530 BlockNumbering.erase(MA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001531 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
1532 MUD->setDefiningAccess(nullptr);
1533 // Invalidate our walker's cache if necessary
1534 if (!isa<MemoryUse>(MA))
1535 Walker->invalidateInfo(MA);
1536 // The call below to erase will destroy MA, so we can't change the order we
1537 // are doing things here
1538 Value *MemoryInst;
1539 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1540 MemoryInst = MUD->getMemoryInst();
1541 } else {
1542 MemoryInst = MA->getBlock();
1543 }
Daniel Berlin5130cc82016-07-31 21:08:20 +00001544 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1545 if (VMA->second == MA)
1546 ValueToMemoryAccess.erase(VMA);
Daniel Berlin60ead052017-01-28 01:23:13 +00001547}
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001548
Daniel Berlin60ead052017-01-28 01:23:13 +00001549/// \brief Properly remove \p MA from all of MemorySSA's lists.
1550///
1551/// Because of the way the intrusive list and use lists work, it is important to
1552/// do removal in the right order.
1553/// ShouldDelete defaults to true, and will cause the memory access to also be
1554/// deleted, not just removed.
1555void MemorySSA::removeFromLists(MemoryAccess *MA, bool ShouldDelete) {
Daniel Berlind602e042017-01-25 20:56:19 +00001556 // The access list owns the reference, so we erase it from the non-owning list
1557 // first.
1558 if (!isa<MemoryUse>(MA)) {
1559 auto DefsIt = PerBlockDefs.find(MA->getBlock());
1560 std::unique_ptr<DefsList> &Defs = DefsIt->second;
1561 Defs->remove(*MA);
1562 if (Defs->empty())
1563 PerBlockDefs.erase(DefsIt);
1564 }
1565
Daniel Berlin60ead052017-01-28 01:23:13 +00001566 // The erase call here will delete it. If we don't want it deleted, we call
1567 // remove instead.
George Burgess IVe0e6e482016-03-02 02:35:04 +00001568 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
Daniel Berlinada263d2016-06-20 20:21:33 +00001569 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin60ead052017-01-28 01:23:13 +00001570 if (ShouldDelete)
1571 Accesses->erase(MA);
1572 else
1573 Accesses->remove(MA);
1574
George Burgess IVe0e6e482016-03-02 02:35:04 +00001575 if (Accesses->empty())
1576 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001577}
1578
George Burgess IVe1100f52016-02-02 22:46:49 +00001579void MemorySSA::print(raw_ostream &OS) const {
1580 MemorySSAAnnotatedWriter Writer(this);
1581 F.print(OS, &Writer);
1582}
1583
Matthias Braun8c209aa2017-01-28 02:02:38 +00001584#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Daniel Berlin78cbd282017-02-20 22:26:03 +00001585LLVM_DUMP_METHOD void MemorySSA::dump() const { print(dbgs()); }
Matthias Braun8c209aa2017-01-28 02:02:38 +00001586#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001587
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001588void MemorySSA::verifyMemorySSA() const {
1589 verifyDefUses(F);
1590 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001591 verifyOrdering(F);
Geoff Berrycdf53332016-08-08 17:52:01 +00001592 Walker->verify(this);
Daniel Berlin14300262016-06-21 18:39:20 +00001593}
1594
1595/// \brief Verify that the order and existence of MemoryAccesses matches the
1596/// order and existence of memory affecting instructions.
1597void MemorySSA::verifyOrdering(Function &F) const {
1598 // Walk all the blocks, comparing what the lookups think and what the access
1599 // lists think, as well as the order in the blocks vs the order in the access
1600 // lists.
1601 SmallVector<MemoryAccess *, 32> ActualAccesses;
Daniel Berlind602e042017-01-25 20:56:19 +00001602 SmallVector<MemoryAccess *, 32> ActualDefs;
Daniel Berlin14300262016-06-21 18:39:20 +00001603 for (BasicBlock &B : F) {
1604 const AccessList *AL = getBlockAccesses(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001605 const auto *DL = getBlockDefs(&B);
Daniel Berlin14300262016-06-21 18:39:20 +00001606 MemoryAccess *Phi = getMemoryAccess(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001607 if (Phi) {
Daniel Berlin14300262016-06-21 18:39:20 +00001608 ActualAccesses.push_back(Phi);
Daniel Berlind602e042017-01-25 20:56:19 +00001609 ActualDefs.push_back(Phi);
1610 }
1611
Daniel Berlin14300262016-06-21 18:39:20 +00001612 for (Instruction &I : B) {
1613 MemoryAccess *MA = getMemoryAccess(&I);
Daniel Berlind602e042017-01-25 20:56:19 +00001614 assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) &&
1615 "We have memory affecting instructions "
1616 "in this block but they are not in the "
1617 "access list or defs list");
1618 if (MA) {
Daniel Berlin14300262016-06-21 18:39:20 +00001619 ActualAccesses.push_back(MA);
Daniel Berlind602e042017-01-25 20:56:19 +00001620 if (isa<MemoryDef>(MA))
1621 ActualDefs.push_back(MA);
1622 }
Daniel Berlin14300262016-06-21 18:39:20 +00001623 }
1624 // Either we hit the assert, really have no accesses, or we have both
Daniel Berlind602e042017-01-25 20:56:19 +00001625 // accesses and an access list.
1626 // Same with defs.
1627 if (!AL && !DL)
Daniel Berlin14300262016-06-21 18:39:20 +00001628 continue;
1629 assert(AL->size() == ActualAccesses.size() &&
1630 "We don't have the same number of accesses in the block as on the "
1631 "access list");
Davide Italiano6c77de02017-01-30 03:16:43 +00001632 assert((DL || ActualDefs.size() == 0) &&
1633 "Either we should have a defs list, or we should have no defs");
Daniel Berlind602e042017-01-25 20:56:19 +00001634 assert((!DL || DL->size() == ActualDefs.size()) &&
1635 "We don't have the same number of defs in the block as on the "
1636 "def list");
Daniel Berlin14300262016-06-21 18:39:20 +00001637 auto ALI = AL->begin();
1638 auto AAI = ActualAccesses.begin();
1639 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1640 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1641 ++ALI;
1642 ++AAI;
1643 }
1644 ActualAccesses.clear();
Daniel Berlind602e042017-01-25 20:56:19 +00001645 if (DL) {
1646 auto DLI = DL->begin();
1647 auto ADI = ActualDefs.begin();
1648 while (DLI != DL->end() && ADI != ActualDefs.end()) {
1649 assert(&*DLI == *ADI && "Not the same defs in the same order");
1650 ++DLI;
1651 ++ADI;
1652 }
1653 }
1654 ActualDefs.clear();
Daniel Berlin14300262016-06-21 18:39:20 +00001655 }
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001656}
1657
George Burgess IVe1100f52016-02-02 22:46:49 +00001658/// \brief Verify the domination properties of MemorySSA by checking that each
1659/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001660void MemorySSA::verifyDomination(Function &F) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001661#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001662 for (BasicBlock &B : F) {
1663 // Phi nodes are attached to basic blocks
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001664 if (MemoryPhi *MP = getMemoryAccess(&B))
1665 for (const Use &U : MP->uses())
1666 assert(dominates(MP, U) && "Memory PHI does not dominate it's uses");
Daniel Berlin7af95872016-08-05 21:47:20 +00001667
George Burgess IVe1100f52016-02-02 22:46:49 +00001668 for (Instruction &I : B) {
1669 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
1670 if (!MD)
1671 continue;
1672
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001673 for (const Use &U : MD->uses())
1674 assert(dominates(MD, U) && "Memory Def does not dominate it's uses");
George Burgess IVe1100f52016-02-02 22:46:49 +00001675 }
1676 }
Daniel Berlin7af95872016-08-05 21:47:20 +00001677#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001678}
1679
1680/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
1681/// appears in the use list of \p Def.
Daniel Berlin7af95872016-08-05 21:47:20 +00001682
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001683void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001684#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001685 // The live on entry use may cause us to get a NULL def here
Daniel Berlin7af95872016-08-05 21:47:20 +00001686 if (!Def)
1687 assert(isLiveOnEntryDef(Use) &&
1688 "Null def but use not point to live on entry def");
1689 else
Daniel Berlinda2f38e2016-08-11 21:26:50 +00001690 assert(is_contained(Def->users(), Use) &&
Daniel Berlin7af95872016-08-05 21:47:20 +00001691 "Did not find use in def's use list");
1692#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001693}
1694
1695/// \brief Verify the immediate use information, by walking all the memory
1696/// accesses and verifying that, for each use, it appears in the
1697/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001698void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001699 for (BasicBlock &B : F) {
1700 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00001701 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00001702 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
1703 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00001704 "Incomplete MemoryPhi Node");
George Burgess IVe1100f52016-02-02 22:46:49 +00001705 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1706 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Daniel Berlin14300262016-06-21 18:39:20 +00001707 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001708
1709 for (Instruction &I : B) {
George Burgess IV66837ab2016-11-01 21:17:46 +00001710 if (MemoryUseOrDef *MA = getMemoryAccess(&I)) {
1711 verifyUseInDefs(MA->getDefiningAccess(), MA);
George Burgess IVe1100f52016-02-02 22:46:49 +00001712 }
1713 }
1714 }
1715}
1716
George Burgess IV66837ab2016-11-01 21:17:46 +00001717MemoryUseOrDef *MemorySSA::getMemoryAccess(const Instruction *I) const {
1718 return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I));
George Burgess IVe1100f52016-02-02 22:46:49 +00001719}
1720
1721MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
George Burgess IV66837ab2016-11-01 21:17:46 +00001722 return cast_or_null<MemoryPhi>(ValueToMemoryAccess.lookup(cast<Value>(BB)));
George Burgess IVe1100f52016-02-02 22:46:49 +00001723}
1724
Daniel Berlin5c46b942016-07-19 22:49:43 +00001725/// Perform a local numbering on blocks so that instruction ordering can be
1726/// determined in constant time.
1727/// TODO: We currently just number in order. If we numbered by N, we could
1728/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
1729/// log2(N) sequences of mixed before and after) without needing to invalidate
1730/// the numbering.
1731void MemorySSA::renumberBlock(const BasicBlock *B) const {
1732 // The pre-increment ensures the numbers really start at 1.
1733 unsigned long CurrentNumber = 0;
1734 const AccessList *AL = getBlockAccesses(B);
1735 assert(AL != nullptr && "Asking to renumber an empty block");
1736 for (const auto &I : *AL)
1737 BlockNumbering[&I] = ++CurrentNumber;
1738 BlockNumberingValid.insert(B);
1739}
1740
George Burgess IVe1100f52016-02-02 22:46:49 +00001741/// \brief Determine, for two memory accesses in the same block,
1742/// whether \p Dominator dominates \p Dominatee.
1743/// \returns True if \p Dominator dominates \p Dominatee.
1744bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
1745 const MemoryAccess *Dominatee) const {
Sebastian Pope1f60b12016-06-10 21:36:41 +00001746
Daniel Berlin5c46b942016-07-19 22:49:43 +00001747 const BasicBlock *DominatorBlock = Dominator->getBlock();
Daniel Berlin5c46b942016-07-19 22:49:43 +00001748
Daniel Berlin19860302016-07-19 23:08:08 +00001749 assert((DominatorBlock == Dominatee->getBlock()) &&
Daniel Berlin5c46b942016-07-19 22:49:43 +00001750 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00001751 // A node dominates itself.
1752 if (Dominatee == Dominator)
1753 return true;
1754
1755 // When Dominatee is defined on function entry, it is not dominated by another
1756 // memory access.
1757 if (isLiveOnEntryDef(Dominatee))
1758 return false;
1759
1760 // When Dominator is defined on function entry, it dominates the other memory
1761 // access.
1762 if (isLiveOnEntryDef(Dominator))
1763 return true;
1764
Daniel Berlin5c46b942016-07-19 22:49:43 +00001765 if (!BlockNumberingValid.count(DominatorBlock))
1766 renumberBlock(DominatorBlock);
George Burgess IVe1100f52016-02-02 22:46:49 +00001767
Daniel Berlin5c46b942016-07-19 22:49:43 +00001768 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
1769 // All numbers start with 1
1770 assert(DominatorNum != 0 && "Block was not numbered properly");
1771 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
1772 assert(DominateeNum != 0 && "Block was not numbered properly");
1773 return DominatorNum < DominateeNum;
George Burgess IVe1100f52016-02-02 22:46:49 +00001774}
1775
George Burgess IV5f308972016-07-19 01:29:15 +00001776bool MemorySSA::dominates(const MemoryAccess *Dominator,
1777 const MemoryAccess *Dominatee) const {
1778 if (Dominator == Dominatee)
1779 return true;
1780
1781 if (isLiveOnEntryDef(Dominatee))
1782 return false;
1783
1784 if (Dominator->getBlock() != Dominatee->getBlock())
1785 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
1786 return locallyDominates(Dominator, Dominatee);
1787}
1788
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001789bool MemorySSA::dominates(const MemoryAccess *Dominator,
1790 const Use &Dominatee) const {
1791 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
1792 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
1793 // The def must dominate the incoming block of the phi.
1794 if (UseBB != Dominator->getBlock())
1795 return DT->dominates(Dominator->getBlock(), UseBB);
1796 // If the UseBB and the DefBB are the same, compare locally.
1797 return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
1798 }
1799 // If it's not a PHI node use, the normal dominates can already handle it.
1800 return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
1801}
1802
George Burgess IVe1100f52016-02-02 22:46:49 +00001803const static char LiveOnEntryStr[] = "liveOnEntry";
1804
1805void MemoryDef::print(raw_ostream &OS) const {
1806 MemoryAccess *UO = getDefiningAccess();
1807
1808 OS << getID() << " = MemoryDef(";
1809 if (UO && UO->getID())
1810 OS << UO->getID();
1811 else
1812 OS << LiveOnEntryStr;
1813 OS << ')';
1814}
1815
1816void MemoryPhi::print(raw_ostream &OS) const {
1817 bool First = true;
1818 OS << getID() << " = MemoryPhi(";
1819 for (const auto &Op : operands()) {
1820 BasicBlock *BB = getIncomingBlock(Op);
1821 MemoryAccess *MA = cast<MemoryAccess>(Op);
1822 if (!First)
1823 OS << ',';
1824 else
1825 First = false;
1826
1827 OS << '{';
1828 if (BB->hasName())
1829 OS << BB->getName();
1830 else
1831 BB->printAsOperand(OS, false);
1832 OS << ',';
1833 if (unsigned ID = MA->getID())
1834 OS << ID;
1835 else
1836 OS << LiveOnEntryStr;
1837 OS << '}';
1838 }
1839 OS << ')';
1840}
1841
1842MemoryAccess::~MemoryAccess() {}
1843
1844void MemoryUse::print(raw_ostream &OS) const {
1845 MemoryAccess *UO = getDefiningAccess();
1846 OS << "MemoryUse(";
1847 if (UO && UO->getID())
1848 OS << UO->getID();
1849 else
1850 OS << LiveOnEntryStr;
1851 OS << ')';
1852}
1853
1854void MemoryAccess::dump() const {
Daniel Berlin78cbd282017-02-20 22:26:03 +00001855// Cannot completely remove virtual function even in release mode.
Matthias Braun8c209aa2017-01-28 02:02:38 +00001856#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
George Burgess IVe1100f52016-02-02 22:46:49 +00001857 print(dbgs());
1858 dbgs() << "\n";
Matthias Braun8c209aa2017-01-28 02:02:38 +00001859#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001860}
1861
Chad Rosier232e29e2016-07-06 21:20:47 +00001862char MemorySSAPrinterLegacyPass::ID = 0;
1863
1864MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
1865 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
1866}
1867
1868void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
1869 AU.setPreservesAll();
1870 AU.addRequired<MemorySSAWrapperPass>();
1871 AU.addPreserved<MemorySSAWrapperPass>();
1872}
1873
1874bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
1875 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
1876 MSSA.print(dbgs());
1877 if (VerifyMemorySSA)
1878 MSSA.verifyMemorySSA();
1879 return false;
1880}
1881
Chandler Carruthdab4eae2016-11-23 17:53:26 +00001882AnalysisKey MemorySSAAnalysis::Key;
George Burgess IVe1100f52016-02-02 22:46:49 +00001883
Daniel Berlin1e98c042016-09-26 17:22:54 +00001884MemorySSAAnalysis::Result MemorySSAAnalysis::run(Function &F,
1885 FunctionAnalysisManager &AM) {
Geoff Berryb96d3b22016-06-01 21:30:40 +00001886 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1887 auto &AA = AM.getResult<AAManager>(F);
Geoff Berry290a13e2016-08-08 18:27:22 +00001888 return MemorySSAAnalysis::Result(make_unique<MemorySSA>(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00001889}
1890
Geoff Berryb96d3b22016-06-01 21:30:40 +00001891PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
1892 FunctionAnalysisManager &AM) {
1893 OS << "MemorySSA for function: " << F.getName() << "\n";
Geoff Berry290a13e2016-08-08 18:27:22 +00001894 AM.getResult<MemorySSAAnalysis>(F).getMSSA().print(OS);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001895
1896 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00001897}
1898
Geoff Berryb96d3b22016-06-01 21:30:40 +00001899PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
1900 FunctionAnalysisManager &AM) {
Geoff Berry290a13e2016-08-08 18:27:22 +00001901 AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001902
1903 return PreservedAnalyses::all();
1904}
1905
1906char MemorySSAWrapperPass::ID = 0;
1907
1908MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
1909 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
1910}
1911
1912void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
1913
1914void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001915 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001916 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
1917 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001918}
1919
Geoff Berryb96d3b22016-06-01 21:30:40 +00001920bool MemorySSAWrapperPass::runOnFunction(Function &F) {
1921 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1922 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1923 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00001924 return false;
1925}
1926
Geoff Berryb96d3b22016-06-01 21:30:40 +00001927void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00001928
Geoff Berryb96d3b22016-06-01 21:30:40 +00001929void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001930 MSSA->print(OS);
1931}
1932
George Burgess IVe1100f52016-02-02 22:46:49 +00001933MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
1934
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001935MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A,
1936 DominatorTree *D)
Daniel Berlind7a7ae02017-04-05 19:01:58 +00001937 : MemorySSAWalker(M), Walker(*M, *A, *D), AutoResetWalker(true) {}
George Burgess IVe1100f52016-02-02 22:46:49 +00001938
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001939MemorySSA::CachingWalker::~CachingWalker() {}
George Burgess IVe1100f52016-02-02 22:46:49 +00001940
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001941void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) {
Daniel Berlind7a7ae02017-04-05 19:01:58 +00001942 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1943 MUD->resetOptimized();
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001944}
1945
George Burgess IVe1100f52016-02-02 22:46:49 +00001946/// \brief Walk the use-def chains starting at \p MA and find
1947/// the MemoryAccess that actually clobbers Loc.
1948///
1949/// \returns our clobbering memory access
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001950MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
1951 MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +00001952 MemoryAccess *New = Walker.findClobber(StartingAccess, Q);
1953#ifdef EXPENSIVE_CHECKS
Daniel Berlind7a7ae02017-04-05 19:01:58 +00001954 MemoryAccess *NewNoCache = Walker.findClobber(StartingAccess, Q);
George Burgess IV5f308972016-07-19 01:29:15 +00001955 assert(NewNoCache == New && "Cache made us hand back a different result?");
1956#endif
1957 if (AutoResetWalker)
1958 resetClobberWalker();
1959 return New;
George Burgess IVe1100f52016-02-02 22:46:49 +00001960}
1961
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001962MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
George Burgess IV013fd732016-10-28 19:22:46 +00001963 MemoryAccess *StartingAccess, const MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001964 if (isa<MemoryPhi>(StartingAccess))
1965 return StartingAccess;
1966
1967 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
1968 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
1969 return StartingUseOrDef;
1970
1971 Instruction *I = StartingUseOrDef->getMemoryInst();
1972
1973 // Conservatively, fences are always clobbers, so don't perform the walk if we
1974 // hit a fence.
David Majnemera940f362016-07-15 17:19:24 +00001975 if (!ImmutableCallSite(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00001976 return StartingUseOrDef;
1977
1978 UpwardsMemoryQuery Q;
1979 Q.OriginalAccess = StartingUseOrDef;
1980 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00001981 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00001982 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00001983
George Burgess IVe1100f52016-02-02 22:46:49 +00001984 // Unlike the other function, do not walk to the def of a def, because we are
1985 // handed something we already believe is the clobbering access.
1986 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
1987 ? StartingUseOrDef->getDefiningAccess()
1988 : StartingUseOrDef;
1989
1990 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00001991 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
1992 DEBUG(dbgs() << *StartingUseOrDef << "\n");
1993 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
1994 DEBUG(dbgs() << *Clobber << "\n");
1995 return Clobber;
1996}
1997
1998MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00001999MemorySSA::CachingWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
2000 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2001 // If this is a MemoryPhi, we can't do anything.
2002 if (!StartingAccess)
2003 return MA;
George Burgess IVe1100f52016-02-02 22:46:49 +00002004
Daniel Berlincd2deac2016-10-20 20:13:45 +00002005 // If this is an already optimized use or def, return the optimized result.
2006 // Note: Currently, we do not store the optimized def result because we'd need
2007 // a separate field, since we can't use it as the defining access.
Daniel Berline33bc312017-04-04 23:43:10 +00002008 if (auto *MUD = dyn_cast<MemoryUseOrDef>(StartingAccess))
2009 if (MUD->isOptimized())
2010 return MUD->getOptimized();
Daniel Berlincd2deac2016-10-20 20:13:45 +00002011
George Burgess IV400ae402016-07-20 19:51:34 +00002012 const Instruction *I = StartingAccess->getMemoryInst();
George Burgess IV5f308972016-07-19 01:29:15 +00002013 UpwardsMemoryQuery Q(I, StartingAccess);
David Majnemera940f362016-07-15 17:19:24 +00002014 // We can't sanely do anything with a fences, they conservatively
George Burgess IVe1100f52016-02-02 22:46:49 +00002015 // clobber all memory, and have no locations to get pointers from to
David Majnemera940f362016-07-15 17:19:24 +00002016 // try to disambiguate.
George Burgess IV5f308972016-07-19 01:29:15 +00002017 if (!Q.IsCall && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002018 return StartingAccess;
2019
George Burgess IV024f3d22016-08-03 19:57:02 +00002020 if (isUseTriviallyOptimizableToLiveOnEntry(*MSSA->AA, I)) {
2021 MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
Daniel Berline33bc312017-04-04 23:43:10 +00002022 if (auto *MUD = dyn_cast<MemoryUseOrDef>(StartingAccess))
2023 MUD->setOptimized(LiveOnEntry);
George Burgess IV024f3d22016-08-03 19:57:02 +00002024 return LiveOnEntry;
2025 }
2026
George Burgess IVe1100f52016-02-02 22:46:49 +00002027 // Start with the thing we already think clobbers this location
2028 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2029
2030 // At this point, DefiningAccess may be the live on entry def.
2031 // If it is, we will not get a better result.
2032 if (MSSA->isLiveOnEntryDef(DefiningAccess))
2033 return DefiningAccess;
2034
2035 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002036 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2037 DEBUG(dbgs() << *DefiningAccess << "\n");
2038 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2039 DEBUG(dbgs() << *Result << "\n");
Daniel Berline33bc312017-04-04 23:43:10 +00002040 if (auto *MUD = dyn_cast<MemoryUseOrDef>(StartingAccess))
2041 MUD->setOptimized(Result);
George Burgess IVe1100f52016-02-02 22:46:49 +00002042
2043 return Result;
2044}
2045
George Burgess IVe1100f52016-02-02 22:46:49 +00002046MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002047DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002048 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2049 return Use->getDefiningAccess();
2050 return MA;
2051}
2052
2053MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
George Burgess IV013fd732016-10-28 19:22:46 +00002054 MemoryAccess *StartingAccess, const MemoryLocation &) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002055 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2056 return Use->getDefiningAccess();
2057 return StartingAccess;
2058}
George Burgess IV5f308972016-07-19 01:29:15 +00002059} // namespace llvm