LLVM 24.0.0git
MemorySSA.cpp
Go to the documentation of this file.
1//===- MemorySSA.cpp - Memory SSA Builder ---------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the MemorySSA class.
10//
11//===----------------------------------------------------------------------===//
12
14#include "AnalysisOptions.h"
15#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/Hashing.h"
20#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/iterator.h"
29#include "llvm/Analysis/Loads.h"
32#include "llvm/Config/llvm-config.h"
34#include "llvm/IR/BasicBlock.h"
35#include "llvm/IR/Dominators.h"
36#include "llvm/IR/Function.h"
37#include "llvm/IR/Instruction.h"
40#include "llvm/IR/LLVMContext.h"
41#include "llvm/IR/Operator.h"
42#include "llvm/IR/PassManager.h"
43#include "llvm/IR/Use.h"
45#include "llvm/Pass.h"
50#include "llvm/Support/Debug.h"
55#include <algorithm>
56#include <cassert>
57#include <iterator>
58#include <memory>
59#include <utility>
60
61using namespace llvm;
62
63#define DEBUG_TYPE "memoryssa"
64
65INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
66 true)
70 true)
71
72// Always verify MemorySSA if expensive checking is enabled.
73#ifdef EXPENSIVE_CHECKS
74bool llvm::VerifyMemorySSA = true;
75#else
77#endif
78
81 cl::Hidden, cl::desc("Enable verification of MemorySSA."));
82
83const static char LiveOnEntryStr[] = "liveOnEntry";
84
85namespace {
86
87/// An assembly annotator class to print Memory SSA information in
88/// comments.
89class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
90 const MemorySSA *MSSA;
91
92public:
93 MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
94
95 void emitBasicBlockStartAnnot(const BasicBlock *BB,
96 formatted_raw_ostream &OS) override {
97 if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
98 OS << "; " << *MA << "\n";
99 }
100
101 void emitInstructionAnnot(const Instruction *I,
102 formatted_raw_ostream &OS) override {
103 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
104 OS << "; " << *MA << "\n";
105 }
106};
107
108/// An assembly annotator class to print Memory SSA information in
109/// comments.
110class MemorySSAWalkerAnnotatedWriter : public AssemblyAnnotationWriter {
111 MemorySSA *MSSA;
112 MemorySSAWalker *Walker;
113 BatchAAResults BAA;
114
115public:
116 MemorySSAWalkerAnnotatedWriter(MemorySSA *M)
117 : MSSA(M), Walker(M->getWalker()), BAA(M->getAA()) {}
118
119 void emitBasicBlockStartAnnot(const BasicBlock *BB,
120 formatted_raw_ostream &OS) override {
121 if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
122 OS << "; " << *MA << "\n";
123 }
124
125 void emitInstructionAnnot(const Instruction *I,
126 formatted_raw_ostream &OS) override {
127 if (MemoryAccess *MA = MSSA->getMemoryAccess(I)) {
128 MemoryAccess *Clobber = Walker->getClobberingMemoryAccess(MA, BAA);
129 OS << "; " << *MA;
130 if (Clobber) {
131 OS << " - clobbered by ";
132 if (MSSA->isLiveOnEntryDef(Clobber))
133 OS << LiveOnEntryStr;
134 else
135 OS << *Clobber;
136 }
137 OS << "\n";
138 }
139 }
140};
141
142} // namespace
143
144namespace {
145
146/// Our current alias analysis API differentiates heavily between calls and
147/// non-calls, and functions called on one usually assert on the other.
148/// This class encapsulates the distinction to simplify other code that wants
149/// "Memory affecting instructions and related data" to use as a key.
150/// For example, this class is used as a densemap key in the use optimizer.
151class MemoryLocOrCall {
152public:
153 bool IsCall = false;
154
155 MemoryLocOrCall(MemoryUseOrDef *MUD)
156 : MemoryLocOrCall(MUD->getMemoryInst()) {}
157 MemoryLocOrCall(const MemoryUseOrDef *MUD)
158 : MemoryLocOrCall(MUD->getMemoryInst()) {}
159
160 MemoryLocOrCall(Instruction *Inst) {
161 if (auto *C = dyn_cast<CallBase>(Inst)) {
162 IsCall = true;
163 Call = C;
164 } else {
165 IsCall = false;
166 // There is no such thing as a memorylocation for a fence inst, and it is
167 // unique in that regard.
168 if (!isa<FenceInst>(Inst))
169 Loc = MemoryLocation::get(Inst);
170 }
171 }
172
173 explicit MemoryLocOrCall(const MemoryLocation &Loc) : Loc(Loc) {}
174
175 const CallBase *getCall() const {
176 assert(IsCall);
177 return Call;
178 }
179
180 MemoryLocation getLoc() const {
181 assert(!IsCall);
182 return Loc;
183 }
184
185 bool operator==(const MemoryLocOrCall &Other) const {
186 if (IsCall != Other.IsCall)
187 return false;
188
189 if (!IsCall)
190 return Loc == Other.Loc;
191
192 if (Call->getCalledOperand() != Other.Call->getCalledOperand())
193 return false;
194
195 return Call->arg_size() == Other.Call->arg_size() &&
196 std::equal(Call->arg_begin(), Call->arg_end(),
197 Other.Call->arg_begin());
198 }
199
200private:
201 union {
202 const CallBase *Call;
203 MemoryLocation Loc;
204 };
205};
206
207} // end anonymous namespace
208
209namespace llvm {
210
211template <> struct DenseMapInfo<MemoryLocOrCall> {
212 static unsigned getHashValue(const MemoryLocOrCall &MLOC) {
213 if (!MLOC.IsCall)
214 return hash_combine(
215 MLOC.IsCall,
217
218 hash_code hash =
220 MLOC.getCall()->getCalledOperand()));
221
222 for (const Value *Arg : MLOC.getCall()->args())
224 return hash;
225 }
226
227 static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS) {
228 return LHS == RHS;
229 }
230};
231
232} // end namespace llvm
233
234/// This does one-way checks to see if Use could theoretically be hoisted above
235/// MayClobber. This will not check the other way around.
236///
237/// This assumes that, for the purposes of MemorySSA, Use comes directly after
238/// MayClobber, with no potentially clobbering operations in between them.
239/// (Where potentially clobbering ops are memory barriers, aliased stores, etc.)
241 const LoadInst *MayClobber) {
242 bool VolatileUse = Use->isVolatile();
243 bool VolatileClobber = MayClobber->isVolatile();
244 // Volatile operations may never be reordered with other volatile operations.
245 if (VolatileUse && VolatileClobber)
246 return false;
247 // Otherwise, volatile doesn't matter here. From the language reference:
248 // 'optimizers may change the order of volatile operations relative to
249 // non-volatile operations.'"
250
251 // If a load is seq_cst, it cannot be moved above other loads. If its ordering
252 // is weaker, it can be moved above other loads. We just need to be sure that
253 // MayClobber isn't an acquire load, because loads can't be moved above
254 // acquire loads.
255 //
256 // Note that this explicitly *does* allow the free reordering of monotonic (or
257 // weaker) loads of the same address.
258 bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent;
259 bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(),
261 return !(SeqCstUse || MayClobberIsAcquire);
262}
263
264template <typename AliasAnalysisType>
265static bool
267 const Instruction *UseInst, AliasAnalysisType &AA) {
268 Instruction *DefInst = MD->getMemoryInst();
269 assert(DefInst && "Defining instruction not actually an instruction");
270
271 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
272 // These intrinsics will show up as affecting memory, but they are just
273 // markers, mostly.
274 //
275 // FIXME: We probably don't actually want MemorySSA to model these at all
276 // (including creating MemoryAccesses for them): we just end up inventing
277 // clobbers where they don't really exist at all. Please see D43269 for
278 // context.
279 switch (II->getIntrinsicID()) {
280 case Intrinsic::allow_runtime_check:
281 case Intrinsic::allow_ubsan_check:
282 case Intrinsic::invariant_start:
283 case Intrinsic::invariant_end:
284 case Intrinsic::assume:
285 case Intrinsic::experimental_noalias_scope_decl:
286 case Intrinsic::pseudoprobe:
287 return false;
288 default:
289 break;
290 }
291 }
292
293 if (auto *CB = dyn_cast_or_null<CallBase>(UseInst)) {
294 ModRefInfo I = AA.getModRefInfo(DefInst, CB);
295 return isModSet(I);
296 }
297
298 if (auto *DefLoad = dyn_cast<LoadInst>(DefInst))
299 if (auto *UseLoad = dyn_cast_or_null<LoadInst>(UseInst))
300 return !areLoadsReorderable(UseLoad, DefLoad);
301
302 ModRefInfo I = AA.getModRefInfo(DefInst, UseLoc);
303 return isModSet(I);
304}
305
306template <typename AliasAnalysisType>
308 const MemoryLocOrCall &UseMLOC,
309 AliasAnalysisType &AA) {
310 // FIXME: This is a temporary hack to allow a single instructionClobbersQuery
311 // to exist while MemoryLocOrCall is pushed through places.
312 if (UseMLOC.IsCall)
314 AA);
315 return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(),
316 AA);
317}
318
319// Return true when MD may alias MU, return false otherwise.
321 AliasAnalysis &AA) {
322 return instructionClobbersQuery(MD, MU, MemoryLocOrCall(MU), AA);
323}
324
325namespace {
326
327struct UpwardsMemoryQuery {
328 // True if our original query started off as a call
329 bool IsCall = false;
330 // The pointer location we started the query with. This will be empty if
331 // IsCall is true.
332 MemoryLocation StartingLoc;
333 // This is the instruction we were querying about.
334 const Instruction *Inst = nullptr;
335 // The MemoryAccess we actually got called with, used to test local domination
336 const MemoryAccess *OriginalAccess = nullptr;
337 bool SkipSelfAccess = false;
338
339 UpwardsMemoryQuery() = default;
340
341 UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
342 : IsCall(isa<CallBase>(Inst)), Inst(Inst), OriginalAccess(Access) {
343 if (!IsCall)
344 StartingLoc = MemoryLocation::get(Inst);
345 }
346};
347
348} // end anonymous namespace
349
350template <typename AliasAnalysisType>
351static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysisType &AA,
352 const Instruction *I) {
353 // If the memory can't be changed, then loads of the memory can't be
354 // clobbered.
355 if (I->hasMetadata(LLVMContext::MD_invariant_load))
356 return true;
357 if (auto *LI = dyn_cast<LoadInst>(I))
358 return !isModSet(AA.getModRefInfoMask(MemoryLocation::get(LI)));
359 return false;
360}
361
362/// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
363/// inbetween `Start` and `ClobberAt` can clobbers `Start`.
364///
365/// This is meant to be as simple and self-contained as possible. Because it
366/// uses no cache, etc., it can be relatively expensive.
367///
368/// \param Start The MemoryAccess that we want to walk from.
369/// \param ClobberAt A clobber for Start.
370/// \param StartLoc The MemoryLocation for Start.
371/// \param MSSA The MemorySSA instance that Start and ClobberAt belong to.
372/// \param Query The UpwardsMemoryQuery we used for our search.
373/// \param AA The AliasAnalysis we used for our search.
374/// \param AllowImpreciseClobber Always false, unless we do relaxed verify.
375
376[[maybe_unused]] static void
378 const MemoryLocation &StartLoc, const MemorySSA &MSSA,
379 const UpwardsMemoryQuery &Query, BatchAAResults &AA,
380 bool AllowImpreciseClobber = false) {
381 assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
382
383 if (MSSA.isLiveOnEntryDef(Start)) {
384 assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
385 "liveOnEntry must clobber itself");
386 return;
387 }
388
389 bool FoundClobber = false;
390 DenseSet<UpwardDefsElem> VisitedPhis;
392 Worklist.push_back({Start, StartLoc, /*MayBeCrossIteration=*/false});
393 // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
394 // is found, complain.
395 while (!Worklist.empty()) {
396 auto MAP = Worklist.pop_back_val();
397 // All we care about is that nothing from Start to ClobberAt clobbers Start.
398 // We learn nothing from revisiting nodes.
399 if (!VisitedPhis.insert(MAP).second)
400 continue;
401
402 for (auto *MA : def_chain(MAP.MA)) {
403 if (MA == ClobberAt) {
404 if (const auto *MD = dyn_cast<MemoryDef>(MA)) {
405 // instructionClobbersQuery isn't essentially free, so don't use `|=`,
406 // since it won't let us short-circuit.
407 //
408 // Also, note that this can't be hoisted out of the `Worklist` loop,
409 // since MD may only act as a clobber for 1 of N MemoryLocations.
410 FoundClobber = FoundClobber || MSSA.isLiveOnEntryDef(MD);
411 if (!FoundClobber) {
412 BatchAACrossIterationScope _(AA, MAP.MayBeCrossIteration);
413 if (instructionClobbersQuery(MD, MAP.Loc, Query.Inst, AA))
414 FoundClobber = true;
415 }
416 }
417 break;
418 }
419
420 // We should never hit liveOnEntry, unless it's the clobber.
421 assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
422
423 if (const auto *MD = dyn_cast<MemoryDef>(MA)) {
424 // If Start is a Def, skip self.
425 if (MD == Start)
426 continue;
427
428 BatchAACrossIterationScope _(AA, MAP.MayBeCrossIteration);
429 assert(!instructionClobbersQuery(MD, MAP.Loc, Query.Inst, AA) &&
430 "Found clobber before reaching ClobberAt!");
431 continue;
432 }
433
434 if (const auto *MU = dyn_cast<MemoryUse>(MA)) {
435 (void)MU;
436 assert (MU == Start &&
437 "Can only find use in def chain if Start is a use");
438 continue;
439 }
440
442
443 // Add reachable phi predecessors
444 for (auto ItB = upward_defs_begin({MA, MAP.Loc, MAP.MayBeCrossIteration},
445 MSSA.getDomTree()),
446 ItE = upward_defs_end();
447 ItB != ItE; ++ItB)
448 if (MSSA.getDomTree().isReachableFromEntry(ItB.getPhiArgBlock()))
449 Worklist.emplace_back(*ItB);
450 }
451 }
452
453 // If the verify is done following an optimization, it's possible that
454 // ClobberAt was a conservative clobbering, that we can now infer is not a
455 // true clobbering access. Don't fail the verify if that's the case.
456 // We do have accesses that claim they're optimized, but could be optimized
457 // further. Updating all these can be expensive, so allow it for now (FIXME).
458 if (AllowImpreciseClobber)
459 return;
460
461 // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
462 // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
463 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
464 "ClobberAt never acted as a clobber");
465}
466
467namespace {
468
469/// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
470/// in one class.
471class ClobberWalker {
472 /// Save a few bytes by using unsigned instead of size_t.
473 using ListIndex = unsigned;
474
475 /// Represents a span of contiguous MemoryDefs, potentially ending in a
476 /// MemoryPhi.
477 struct DefPath {
478 MemoryLocation Loc;
479 // Note that, because we always walk in reverse, Last will always dominate
480 // First. Also note that First and Last are inclusive.
481 MemoryAccess *First;
482 MemoryAccess *Last;
483 std::optional<ListIndex> Previous;
484 bool MayBeCrossIteration;
485
486 DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
487 bool MayBeCrossIteration, std::optional<ListIndex> Previous)
488 : Loc(Loc), First(First), Last(Last), Previous(Previous),
489 MayBeCrossIteration(MayBeCrossIteration) {}
490
491 DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
492 bool MayBeCrossIteration, std::optional<ListIndex> Previous)
493 : DefPath(Loc, Init, Init, MayBeCrossIteration, Previous) {}
494 };
495
496 const MemorySSA &MSSA;
497 DominatorTree &DT;
498 BatchAAResults *AA;
499 UpwardsMemoryQuery *Query;
500 unsigned *UpwardWalkLimit;
501
502 // Phi optimization bookkeeping:
503 // List of DefPath to process during the current phi optimization walk.
505 // List of visited <Access, Location> pairs; we can skip paths already
506 // visited with the same memory location.
507 DenseSet<UpwardDefsElem> VisitedPhis;
508
509 /// Find the nearest def or phi that `From` can legally be optimized to.
510 const MemoryAccess *getWalkTarget(const MemoryPhi *From) const {
511 assert(From->getNumOperands() && "Phi with no operands?");
512
513 BasicBlock *BB = From->getBlock();
514 MemoryAccess *Result = MSSA.getLiveOnEntryDef();
515 DomTreeNode *Node = DT.getNode(BB);
516 while ((Node = Node->getIDom())) {
517 auto *Defs = MSSA.getBlockDefs(Node->getBlock());
518 if (Defs)
519 return &*Defs->rbegin();
520 }
521 return Result;
522 }
523
524 /// Result of calling walkToPhiOrClobber.
525 struct UpwardsWalkResult {
526 /// The "Result" of the walk. Either a clobber, the last thing we walked, or
527 /// both. Include alias info when clobber found.
528 MemoryAccess *Result;
529 bool IsKnownClobber;
530 };
531
532 /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
533 /// This will update Desc.Last as it walks. It will (optionally) also stop at
534 /// StopAt.
535 ///
536 /// This does not test for whether StopAt is a clobber
537 UpwardsWalkResult
538 walkToPhiOrClobber(DefPath &Desc, const MemoryAccess *StopAt = nullptr,
539 const MemoryAccess *SkipStopAt = nullptr) const {
540 assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
541 assert(UpwardWalkLimit && "Need a valid walk limit");
542 bool LimitAlreadyReached = false;
543 // (*UpwardWalkLimit) may be 0 here, due to the loop in tryOptimizePhi. Set
544 // it to 1. This will not do any alias() calls. It either returns in the
545 // first iteration in the loop below, or is set back to 0 if all def chains
546 // are free of MemoryDefs.
547 if (!*UpwardWalkLimit) {
548 *UpwardWalkLimit = 1;
549 LimitAlreadyReached = true;
550 }
551
552 for (MemoryAccess *Current : def_chain(Desc.Last)) {
553 Desc.Last = Current;
554 if (Current == StopAt || Current == SkipStopAt)
555 return {Current, false};
556
557 if (auto *MD = dyn_cast<MemoryDef>(Current)) {
558 if (MSSA.isLiveOnEntryDef(MD))
559 return {MD, true};
560
561 if (!--*UpwardWalkLimit)
562 return {Current, true};
563
564 BatchAACrossIterationScope _(*AA, Desc.MayBeCrossIteration);
565 if (instructionClobbersQuery(MD, Desc.Loc, Query->Inst, *AA))
566 return {MD, true};
567 }
568 }
569
570 if (LimitAlreadyReached)
571 *UpwardWalkLimit = 0;
572
573 assert(isa<MemoryPhi>(Desc.Last) &&
574 "Ended at a non-clobber that's not a phi?");
575 return {Desc.Last, false};
576 }
577
578 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
579 ListIndex PriorNode, bool MayBeCrossIteration) {
580 auto UpwardDefsBegin =
581 upward_defs_begin({Phi, Paths[PriorNode].Loc, MayBeCrossIteration}, DT);
582 auto UpwardDefs = make_range(UpwardDefsBegin, upward_defs_end());
583 for (const UpwardDefsElem &E : UpwardDefs) {
584 PausedSearches.push_back(Paths.size());
585 Paths.emplace_back(E.Loc, E.MA, E.MayBeCrossIteration, PriorNode);
586 }
587 }
588
589 /// Represents a search that terminated after finding a clobber. This clobber
590 /// may or may not be present in the path of defs from LastNode..SearchStart,
591 /// since it may have been retrieved from cache.
592 struct TerminatedPath {
593 MemoryAccess *Clobber;
594 ListIndex LastNode;
595 };
596
597 /// Get an access that keeps us from optimizing to the given phi.
598 ///
599 /// PausedSearches is an array of indices into the Paths array. Its incoming
600 /// value is the indices of searches that stopped at the last phi optimization
601 /// target. It's left in an unspecified state.
602 ///
603 /// If this returns std::nullopt, NewPaused is a vector of searches that
604 /// terminated at StopWhere. Otherwise, NewPaused is left in an unspecified
605 /// state.
606 std::optional<TerminatedPath>
607 getBlockingAccess(const MemoryAccess *StopWhere,
608 SmallVectorImpl<ListIndex> &PausedSearches,
609 SmallVectorImpl<ListIndex> &NewPaused,
610 SmallVectorImpl<TerminatedPath> &Terminated) {
611 assert(!PausedSearches.empty() && "No searches to continue?");
612
613 // BFS vs DFS really doesn't make a difference here, so just do a DFS with
614 // PausedSearches as our stack.
615 while (!PausedSearches.empty()) {
616 ListIndex PathIndex = PausedSearches.pop_back_val();
617 DefPath &Node = Paths[PathIndex];
618
619 // If we've already visited this path with this MemoryLocation, we don't
620 // need to do so again.
621 //
622 // NOTE: That we just drop these paths on the ground makes caching
623 // behavior sporadic. e.g. given a diamond:
624 // A
625 // B C
626 // D
627 //
628 // ...If we walk D, B, A, C, we'll only cache the result of phi
629 // optimization for A, B, and D; C will be skipped because it dies here.
630 // This arguably isn't the worst thing ever, since:
631 // - We generally query things in a top-down order, so if we got below D
632 // without needing cache entries for {C, MemLoc}, then chances are
633 // that those cache entries would end up ultimately unused.
634 // - We still cache things for A, so C only needs to walk up a bit.
635 // If this behavior becomes problematic, we can fix without a ton of extra
636 // work.
637 if (!VisitedPhis.insert({Node.Last, Node.Loc, Node.MayBeCrossIteration})
638 .second)
639 continue;
640
641 const MemoryAccess *SkipStopWhere = nullptr;
642 if (Query->SkipSelfAccess && Node.Loc == Query->StartingLoc) {
643 assert(isa<MemoryDef>(Query->OriginalAccess));
644 SkipStopWhere = Query->OriginalAccess;
645 }
646
647 UpwardsWalkResult Res = walkToPhiOrClobber(Node,
648 /*StopAt=*/StopWhere,
649 /*SkipStopAt=*/SkipStopWhere);
650 if (Res.IsKnownClobber) {
651 assert(Res.Result != StopWhere && Res.Result != SkipStopWhere);
652
653 // If this wasn't a cache hit, we hit a clobber when walking. That's a
654 // failure.
655 TerminatedPath Term{Res.Result, PathIndex};
656 if (!MSSA.dominates(Res.Result, StopWhere))
657 return Term;
658
659 // Otherwise, it's a valid thing to potentially optimize to.
660 Terminated.push_back(Term);
661 continue;
662 }
663
664 if (Res.Result == StopWhere || Res.Result == SkipStopWhere) {
665 // We've hit our target. Save this path off for if we want to continue
666 // walking. If we are in the mode of skipping the OriginalAccess, and
667 // we've reached back to the OriginalAccess, do not save path, we've
668 // just looped back to self.
669 if (Res.Result != SkipStopWhere)
670 NewPaused.push_back(PathIndex);
671 continue;
672 }
673
674 assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
675 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex,
676 Node.MayBeCrossIteration);
677 }
678
679 return std::nullopt;
680 }
681
682 template <typename T, typename Walker>
683 struct generic_def_path_iterator
684 : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
685 std::forward_iterator_tag, T *> {
686 generic_def_path_iterator() = default;
687 generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
688
689 T &operator*() const { return curNode(); }
690
691 generic_def_path_iterator &operator++() {
692 N = curNode().Previous;
693 return *this;
694 }
695
696 bool operator==(const generic_def_path_iterator &O) const {
697 if (N.has_value() != O.N.has_value())
698 return false;
699 return !N || *N == *O.N;
700 }
701
702 private:
703 T &curNode() const { return W->Paths[*N]; }
704
705 Walker *W = nullptr;
706 std::optional<ListIndex> N;
707 };
708
709 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
710
711 iterator_range<def_path_iterator> def_path(ListIndex From) {
712 return make_range(def_path_iterator(this, From), def_path_iterator());
713 }
714
715 struct OptznResult {
716 /// The path that contains our result.
717 TerminatedPath PrimaryClobber;
718 /// The paths that we can legally cache back from, but that aren't
719 /// necessarily the result of the Phi optimization.
720 SmallVector<TerminatedPath, 4> OtherClobbers;
721 };
722
723 ListIndex defPathIndex(const DefPath &N) const {
724 // The assert looks nicer if we don't need to do &N
725 const DefPath *NP = &N;
726 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
727 "Out of bounds DefPath!");
728 return NP - &Paths.front();
729 }
730
731 /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
732 /// that act as legal clobbers. Note that this won't return *all* clobbers.
733 ///
734 /// Phi optimization algorithm tl;dr:
735 /// - Find the earliest def/phi, A, we can optimize to
736 /// - Find if all paths from the starting memory access ultimately reach A
737 /// - If not, optimization isn't possible.
738 /// - Otherwise, walk from A to another clobber or phi, A'.
739 /// - If A' is a def, we're done.
740 /// - If A' is a phi, try to optimize it.
741 ///
742 /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
743 /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
744 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
745 const MemoryLocation &Loc) {
746 assert(Paths.empty() && VisitedPhis.empty() &&
747 "Reset the optimization state.");
748
749 Paths.emplace_back(Loc, Start, Phi, /*MayBeCrossIteration=*/false,
750 std::nullopt);
751 // Stores how many "valid" optimization nodes we had prior to calling
752 // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
753 auto PriorPathsSize = Paths.size();
754
755 SmallVector<ListIndex, 16> PausedSearches;
757 SmallVector<TerminatedPath, 4> TerminatedPaths;
758
759 addSearches(Phi, PausedSearches, 0, /*MayBeCrossIteration=*/false);
760
761 // Moves the TerminatedPath with the "most dominated" Clobber to the end of
762 // Paths.
763 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
764 assert(!Paths.empty() && "Need a path to move");
765 auto Dom = Paths.begin();
766 for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
767 if (!MSSA.dominates(I->Clobber, Dom->Clobber))
768 Dom = I;
769 auto Last = Paths.end() - 1;
770 if (Last != Dom)
771 std::iter_swap(Last, Dom);
772 };
773
774 MemoryPhi *Current = Phi;
775 while (true) {
776 assert(!MSSA.isLiveOnEntryDef(Current) &&
777 "liveOnEntry wasn't treated as a clobber?");
778
779 const auto *Target = getWalkTarget(Current);
780 // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
781 // optimization for the prior phi.
782 assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
783 return MSSA.dominates(P.Clobber, Target);
784 }));
785
786 // FIXME: This is broken, because the Blocker may be reported to be
787 // liveOnEntry, and we'll happily wait for that to disappear (read: never)
788 // For the moment, this is fine, since we do nothing with blocker info.
789 if (std::optional<TerminatedPath> Blocker = getBlockingAccess(
790 Target, PausedSearches, NewPaused, TerminatedPaths)) {
791
792 // Find the node we started at. We can't search based on N->Last, since
793 // we may have gone around a loop with a different MemoryLocation.
794 auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
795 return defPathIndex(N) < PriorPathsSize;
796 });
797 assert(Iter != def_path_iterator());
798
799 DefPath &CurNode = *Iter;
800 assert(CurNode.Last == Current);
801
802 // Two things:
803 // A. We can't reliably cache all of NewPaused back. Consider a case
804 // where we have two paths in NewPaused; one of which can't optimize
805 // above this phi, whereas the other can. If we cache the second path
806 // back, we'll end up with suboptimal cache entries. We can handle
807 // cases like this a bit better when we either try to find all
808 // clobbers that block phi optimization, or when our cache starts
809 // supporting unfinished searches.
810 // B. We can't reliably cache TerminatedPaths back here without doing
811 // extra checks; consider a case like:
812 // T
813 // / \
814 // D C
815 // \ /
816 // S
817 // Where T is our target, C is a node with a clobber on it, D is a
818 // diamond (with a clobber *only* on the left or right node, N), and
819 // S is our start. Say we walk to D, through the node opposite N
820 // (read: ignoring the clobber), and see a cache entry in the top
821 // node of D. That cache entry gets put into TerminatedPaths. We then
822 // walk up to C (N is later in our worklist), find the clobber, and
823 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
824 // the bottom part of D to the cached clobber, ignoring the clobber
825 // in N. Again, this problem goes away if we start tracking all
826 // blockers for a given phi optimization.
827 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
828 return {Result, {}};
829 }
830
831 // If there's nothing left to search, then all paths led to valid clobbers
832 // that we got from our cache; pick the nearest to the start, and allow
833 // the rest to be cached back.
834 if (NewPaused.empty()) {
835 MoveDominatedPathToEnd(TerminatedPaths);
836 TerminatedPath Result = TerminatedPaths.pop_back_val();
837 return {Result, std::move(TerminatedPaths)};
838 }
839
840 MemoryAccess *DefChainEnd = nullptr;
842 for (ListIndex Paused : NewPaused) {
843 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
844 if (WR.IsKnownClobber)
845 Clobbers.push_back({WR.Result, Paused});
846 else
847 // Micro-opt: If we hit the end of the chain, save it.
848 DefChainEnd = WR.Result;
849 }
850
851 if (!TerminatedPaths.empty()) {
852 // If we couldn't find the dominating phi/liveOnEntry in the above loop,
853 // do it now.
854 if (!DefChainEnd)
855 for (auto *MA : def_chain(const_cast<MemoryAccess *>(Target)))
856 DefChainEnd = MA;
857 assert(DefChainEnd && "Failed to find dominating phi/liveOnEntry");
858
859 // If any of the terminated paths don't dominate the phi we'll try to
860 // optimize, we need to figure out what they are and quit.
861 const BasicBlock *ChainBB = DefChainEnd->getBlock();
862 for (const TerminatedPath &TP : TerminatedPaths) {
863 // Because we know that DefChainEnd is as "high" as we can go, we
864 // don't need local dominance checks; BB dominance is sufficient.
865 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
866 Clobbers.push_back(TP);
867 }
868 }
869
870 // If we have clobbers in the def chain, find the one closest to Current
871 // and quit.
872 if (!Clobbers.empty()) {
873 MoveDominatedPathToEnd(Clobbers);
874 TerminatedPath Result = Clobbers.pop_back_val();
875 return {Result, std::move(Clobbers)};
876 }
877
878 assert(all_of(NewPaused,
879 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
880
881 // Because liveOnEntry is a clobber, this must be a phi.
882 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
883
884 PriorPathsSize = Paths.size();
885 PausedSearches.clear();
886 for (ListIndex I : NewPaused)
887 addSearches(DefChainPhi, PausedSearches, I,
888 Paths[I].MayBeCrossIteration);
889 NewPaused.clear();
890
891 Current = DefChainPhi;
892 }
893 }
894
895 void verifyOptResult(const OptznResult &R) const {
896 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
897 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
898 }));
899 }
900
901 void resetPhiOptznState() {
902 Paths.clear();
903 VisitedPhis.clear();
904 }
905
906public:
907 ClobberWalker(const MemorySSA &MSSA, DominatorTree &DT)
908 : MSSA(MSSA), DT(DT) {}
909
910 /// Finds the nearest clobber for the given query, optimizing phis if
911 /// possible.
912 MemoryAccess *findClobber(BatchAAResults &BAA, MemoryAccess *Start,
913 UpwardsMemoryQuery &Q, unsigned &UpWalkLimit) {
914 AA = &BAA;
915 Query = &Q;
916 UpwardWalkLimit = &UpWalkLimit;
917 // Starting limit must be > 0.
918 if (!UpWalkLimit)
919 UpWalkLimit++;
920
921 MemoryAccess *Current = Start;
922 // This walker pretends uses don't exist. If we're handed one, silently grab
923 // its def. (This has the nice side-effect of ensuring we never cache uses)
924 if (auto *MU = dyn_cast<MemoryUse>(Start))
925 Current = MU->getDefiningAccess();
926
927 DefPath FirstDesc(Q.StartingLoc, Current, Current,
928 /*MayBeCrossIteration=*/false, std::nullopt);
929 // Fast path for the overly-common case (no crazy phi optimization
930 // necessary)
931 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
932 MemoryAccess *Result;
933 if (WalkResult.IsKnownClobber) {
934 Result = WalkResult.Result;
935 } else {
936 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
937 Current, Q.StartingLoc);
938 verifyOptResult(OptRes);
939 resetPhiOptznState();
940 Result = OptRes.PrimaryClobber.Clobber;
941 }
942
943#ifdef EXPENSIVE_CHECKS
944 if (!Q.SkipSelfAccess && *UpwardWalkLimit > 0)
945 checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, BAA);
946#endif
947 return Result;
948 }
949};
950
951struct RenamePassData {
952 DomTreeNode *DTN;
953 DomTreeNode::const_iterator ChildIt;
954 MemoryAccess *IncomingVal;
955
956 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
957 MemoryAccess *M)
958 : DTN(D), ChildIt(It), IncomingVal(M) {}
959
960 void swap(RenamePassData &RHS) {
961 std::swap(DTN, RHS.DTN);
962 std::swap(ChildIt, RHS.ChildIt);
963 std::swap(IncomingVal, RHS.IncomingVal);
964 }
965};
966
967} // end anonymous namespace
968
969namespace llvm {
970
972 ClobberWalker Walker;
973 MemorySSA *MSSA;
974
975public:
976 ClobberWalkerBase(MemorySSA *M, DominatorTree *D) : Walker(*M, *D), MSSA(M) {}
977
979 const MemoryLocation &,
980 BatchAAResults &, unsigned &);
981 // Third argument (bool), defines whether the clobber search should skip the
982 // original queried access. If true, there will be a follow-up query searching
983 // for a clobber access past "self". Note that the Optimized access is not
984 // updated if a new clobber is found by this SkipSelf search. If this
985 // additional query becomes heavily used we may decide to cache the result.
986 // Walker instantiations will decide how to set the SkipSelf bool.
988 unsigned &, bool,
989 bool UseInvariantGroup = true);
990};
991
992/// A MemorySSAWalker that does AA walks to disambiguate accesses. It no
993/// longer does caching on its own, but the name has been retained for the
994/// moment.
996 ClobberWalkerBase *Walker;
997
998public:
1001 ~CachingWalker() override = default;
1002
1004
1006 unsigned &UWL) {
1007 return Walker->getClobberingMemoryAccessBase(MA, BAA, UWL, false);
1008 }
1010 const MemoryLocation &Loc,
1011 BatchAAResults &BAA, unsigned &UWL) {
1012 return Walker->getClobberingMemoryAccessBase(MA, Loc, BAA, UWL);
1013 }
1014 // This method is not accessible outside of this file.
1016 MemoryAccess *MA, BatchAAResults &BAA, unsigned &UWL) {
1017 return Walker->getClobberingMemoryAccessBase(MA, BAA, UWL, false, false);
1018 }
1019
1021 BatchAAResults &BAA) override {
1022 unsigned UpwardWalkLimit = MSSA->Opts.memssa_check_limit;
1023 return getClobberingMemoryAccess(MA, BAA, UpwardWalkLimit);
1024 }
1026 const MemoryLocation &Loc,
1027 BatchAAResults &BAA) override {
1028 unsigned UpwardWalkLimit = MSSA->Opts.memssa_check_limit;
1029 return getClobberingMemoryAccess(MA, Loc, BAA, UpwardWalkLimit);
1030 }
1031
1032 void invalidateInfo(MemoryAccess *MA) override {
1033 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1034 MUD->resetOptimized();
1035 }
1036};
1037
1039 ClobberWalkerBase *Walker;
1040
1041public:
1044 ~SkipSelfWalker() override = default;
1045
1047
1049 unsigned &UWL) {
1050 return Walker->getClobberingMemoryAccessBase(MA, BAA, UWL, true);
1051 }
1053 const MemoryLocation &Loc,
1054 BatchAAResults &BAA, unsigned &UWL) {
1055 return Walker->getClobberingMemoryAccessBase(MA, Loc, BAA, UWL);
1056 }
1057
1059 BatchAAResults &BAA) override {
1060 unsigned UpwardWalkLimit = MSSA->Opts.memssa_check_limit;
1061 return getClobberingMemoryAccess(MA, BAA, UpwardWalkLimit);
1062 }
1064 const MemoryLocation &Loc,
1065 BatchAAResults &BAA) override {
1066 unsigned UpwardWalkLimit = MSSA->Opts.memssa_check_limit;
1067 return getClobberingMemoryAccess(MA, Loc, BAA, UpwardWalkLimit);
1068 }
1069
1070 void invalidateInfo(MemoryAccess *MA) override {
1071 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1072 MUD->resetOptimized();
1073 }
1074};
1075
1076} // end namespace llvm
1077
1078void MemorySSA::renameSuccessorPhis(BasicBlock *BB, MemoryAccess *IncomingVal,
1079 bool RenameAllUses) {
1080 // Pass through values to our successors
1081 for (const BasicBlock *S : successors(BB)) {
1082 auto It = PerBlockAccesses.find(S);
1083 // Rename the phi nodes in our successor block
1084 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1085 continue;
1086 AccessList *Accesses = It->second.get();
1087 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1088 if (RenameAllUses) {
1089 bool ReplacementDone = false;
1090 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1091 if (Phi->getIncomingBlock(I) == BB) {
1092 Phi->setIncomingValue(I, IncomingVal);
1093 ReplacementDone = true;
1094 }
1095 (void) ReplacementDone;
1096 assert(ReplacementDone && "Incomplete phi during partial rename");
1097 } else
1098 Phi->addIncoming(IncomingVal, BB);
1099 }
1100}
1101
1102/// Rename a single basic block into MemorySSA form.
1103/// Uses the standard SSA renaming algorithm.
1104/// \returns The new incoming value.
1105MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB, MemoryAccess *IncomingVal,
1106 bool RenameAllUses) {
1107 auto It = PerBlockAccesses.find(BB);
1108 // Skip most processing if the list is empty.
1109 if (It != PerBlockAccesses.end()) {
1110 AccessList *Accesses = It->second.get();
1111 for (MemoryAccess &L : *Accesses) {
1112 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) {
1113 if (MUD->getDefiningAccess() == nullptr || RenameAllUses)
1114 MUD->setDefiningAccess(IncomingVal);
1115 if (isa<MemoryDef>(&L))
1116 IncomingVal = &L;
1117 } else {
1118 IncomingVal = &L;
1119 }
1120 }
1121 }
1122 return IncomingVal;
1123}
1124
1125/// This is the standard SSA renaming algorithm.
1126///
1127/// We walk the dominator tree in preorder, renaming accesses, and then filling
1128/// in phi nodes in our successors.
1129void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
1131 bool SkipVisited, bool RenameAllUses) {
1132 assert(Root && "Trying to rename accesses in an unreachable block");
1133
1135 // Skip everything if we already renamed this block and we are skipping.
1136 // Note: You can't sink this into the if, because we need it to occur
1137 // regardless of whether we skip blocks or not.
1138 bool AlreadyVisited = !Visited.insert(Root->getBlock()).second;
1139 if (SkipVisited && AlreadyVisited)
1140 return;
1141
1142 IncomingVal = renameBlock(Root->getBlock(), IncomingVal, RenameAllUses);
1143 renameSuccessorPhis(Root->getBlock(), IncomingVal, RenameAllUses);
1144 WorkStack.push_back({Root, Root->begin(), IncomingVal});
1145
1146 while (!WorkStack.empty()) {
1147 DomTreeNode *Node = WorkStack.back().DTN;
1148 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
1149 IncomingVal = WorkStack.back().IncomingVal;
1150
1151 if (ChildIt == Node->end()) {
1152 WorkStack.pop_back();
1153 } else {
1154 DomTreeNode *Child = *ChildIt;
1155 ++WorkStack.back().ChildIt;
1156 BasicBlock *BB = Child->getBlock();
1157 // Note: You can't sink this into the if, because we need it to occur
1158 // regardless of whether we skip blocks or not.
1159 AlreadyVisited = !Visited.insert(BB).second;
1160 if (SkipVisited && AlreadyVisited) {
1161 // We already visited this during our renaming, which can happen when
1162 // being asked to rename multiple blocks. Figure out the incoming val,
1163 // which is the last def.
1164 // Incoming value can only change if there is a block def, and in that
1165 // case, it's the last block def in the list.
1166 if (auto *BlockDefs = getBlockDefs(BB))
1167 IncomingVal = &*BlockDefs->rbegin();
1168 } else
1169 IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses);
1170 renameSuccessorPhis(BB, IncomingVal, RenameAllUses);
1171 WorkStack.push_back({Child, Child->begin(), IncomingVal});
1172 }
1173 }
1174}
1175
1176/// This handles unreachable block accesses by deleting phi nodes in
1177/// unreachable blocks, and marking all other unreachable MemoryAccess's as
1178/// being uses of the live on entry definition.
1179void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
1180 assert(!DT->isReachableFromEntry(BB) &&
1181 "Reachable block found while handling unreachable blocks");
1182
1183 // Make sure phi nodes in our reachable successors end up with a
1184 // LiveOnEntryDef for our incoming edge, even though our block is forward
1185 // unreachable. We could just disconnect these blocks from the CFG fully,
1186 // but we do not right now.
1187 for (const BasicBlock *S : successors(BB)) {
1188 if (!DT->isReachableFromEntry(S))
1189 continue;
1190 auto It = PerBlockAccesses.find(S);
1191 // Rename the phi nodes in our successor block
1192 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1193 continue;
1194 AccessList *Accesses = It->second.get();
1195 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1196 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1197 }
1198
1199 auto It = PerBlockAccesses.find(BB);
1200 if (It == PerBlockAccesses.end())
1201 return;
1202
1203 auto &Accesses = It->second;
1204 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1205 auto Next = std::next(AI);
1206 // If we have a phi, just remove it. We are going to replace all
1207 // users with live on entry.
1208 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1209 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1210 else
1211 Accesses->erase(AI);
1212 AI = Next;
1213 }
1214}
1215
1217 : Opts(getAnalysisOptions(Func)), DT(DT), F(&Func), LiveOnEntryDef(nullptr),
1218 Walker(nullptr), SkipWalker(nullptr) {
1219 // Build MemorySSA using a batch alias analysis. This reuses the internal
1220 // state that AA collects during an alias()/getModRefInfo() call. This is
1221 // safe because there are no CFG changes while building MemorySSA and can
1222 // significantly reduce the time spent by the compiler in AA, because we will
1223 // make queries about all the instructions in the Function.
1224 assert(AA && "No alias analysis?");
1225 BatchAAResults BatchAA(*AA);
1226 buildMemorySSA(BatchAA, iterator_range(F->begin(), F->end()));
1227 // Intentionally leave AA to nullptr while building so we don't accidentally
1228 // use non-batch AliasAnalysis.
1229 this->AA = AA;
1230 // Also create the walker here.
1231 getWalker();
1232}
1233
1235 : Opts(getAnalysisOptions(L)), DT(DT), L(&L), LiveOnEntryDef(nullptr),
1236 Walker(nullptr), SkipWalker(nullptr) {
1237 // Build MemorySSA using a batch alias analysis. This reuses the internal
1238 // state that AA collects during an alias()/getModRefInfo() call. This is
1239 // safe because there are no CFG changes while building MemorySSA and can
1240 // significantly reduce the time spent by the compiler in AA, because we will
1241 // make queries about all the instructions in the Function.
1242 assert(AA && "No alias analysis?");
1243 BatchAAResults BatchAA(*AA);
1244 buildMemorySSA(
1245 BatchAA, map_range(L.blocks(), [](const BasicBlock *BB) -> BasicBlock & {
1246 return *const_cast<BasicBlock *>(BB);
1247 }));
1248 // Intentionally leave AA to nullptr while building so we don't accidentally
1249 // use non-batch AliasAnalysis.
1250 this->AA = AA;
1251 // Also create the walker here.
1252 getWalker();
1253}
1254
1256 // Drop all our references
1257 for (const auto &Pair : PerBlockAccesses)
1258 for (MemoryAccess &MA : *Pair.second)
1259 MA.dropAllReferences();
1260}
1261
1262MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
1263 auto Res = PerBlockAccesses.try_emplace(BB);
1264
1265 if (Res.second)
1266 Res.first->second = std::make_unique<AccessList>();
1267 return Res.first->second.get();
1268}
1269
1270MemorySSA::DefsList *MemorySSA::getOrCreateDefsList(const BasicBlock *BB) {
1271 auto Res = PerBlockDefs.try_emplace(BB);
1272
1273 if (Res.second)
1274 Res.first->second = std::make_unique<DefsList>();
1275 return Res.first->second.get();
1276}
1277
1278namespace llvm {
1279
1280/// This class is a batch walker of all MemoryUse's in the program, and points
1281/// their defining access at the thing that actually clobbers them. Because it
1282/// is a batch walker that touches everything, it does not operate like the
1283/// other walkers. This walker is basically performing a top-down SSA renaming
1284/// pass, where the version stack is used as the cache. This enables it to be
1285/// significantly more time and memory efficient than using the regular walker,
1286/// which is walking bottom-up.
1288public:
1290 DominatorTree *DT)
1291 : MSSA(MSSA), Walker(Walker), AA(BAA), DT(DT) {}
1292
1293 void optimizeUses();
1294
1295private:
1296 /// This represents where a given memorylocation is in the stack.
1297 struct MemlocStackInfo {
1298 // This essentially is keeping track of versions of the stack. Whenever
1299 // the stack changes due to pushes or pops, these versions increase.
1300 unsigned long StackEpoch;
1301 unsigned long PopEpoch;
1302 // This is the lower bound of places on the stack to check. It is equal to
1303 // the place the last stack walk ended.
1304 // Note: Correctness depends on this being initialized to 0, which densemap
1305 // does
1306 unsigned long LowerBound;
1307 const BasicBlock *LowerBoundBlock;
1308 // This is where the last walk for this memory location ended.
1309 unsigned long LastKill;
1310 bool LastKillValid;
1311 };
1312
1313 void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1316
1317 MemorySSA *MSSA;
1318 CachingWalker *Walker;
1320 DominatorTree *DT;
1321};
1322
1323} // end namespace llvm
1324
1325/// Optimize the uses in a given block This is basically the SSA renaming
1326/// algorithm, with one caveat: We are able to use a single stack for all
1327/// MemoryUses. This is because the set of *possible* reaching MemoryDefs is
1328/// the same for every MemoryUse. The *actual* clobbering MemoryDef is just
1329/// going to be some position in that stack of possible ones.
1330///
1331/// We track the stack positions that each MemoryLocation needs
1332/// to check, and last ended at. This is because we only want to check the
1333/// things that changed since last time. The same MemoryLocation should
1334/// get clobbered by the same store (getModRefInfo does not use invariantness or
1335/// things like this, and if they start, we can modify MemoryLocOrCall to
1336/// include relevant data)
1337void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1338 const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1339 SmallVectorImpl<MemoryAccess *> &VersionStack,
1341
1342 /// If no accesses, nothing to do.
1343 MemorySSA::AccessList *Accesses = MSSA->getBlockAccesses(BB);
1344 if (Accesses == nullptr)
1345 return;
1346
1347 // Pop everything that doesn't dominate the current block off the stack,
1348 // increment the PopEpoch to account for this.
1349 while (true) {
1350 assert(
1351 !VersionStack.empty() &&
1352 "Version stack should have liveOnEntry sentinel dominating everything");
1353 BasicBlock *BackBlock = VersionStack.back()->getBlock();
1354 if (DT->dominates(BackBlock, BB))
1355 break;
1356 while (VersionStack.back()->getBlock() == BackBlock)
1357 VersionStack.pop_back();
1358 ++PopEpoch;
1359 }
1360
1361 for (MemoryAccess &MA : *Accesses) {
1362 auto *MU = dyn_cast<MemoryUse>(&MA);
1363 if (!MU) {
1364 VersionStack.push_back(&MA);
1365 ++StackEpoch;
1366 continue;
1367 }
1368
1369 if (MU->isOptimized())
1370 continue;
1371
1372 MemoryLocOrCall UseMLOC(MU);
1373 auto &LocInfo = LocStackInfo[UseMLOC];
1374 // If the pop epoch changed, it means we've removed stuff from top of
1375 // stack due to changing blocks. We may have to reset the lower bound or
1376 // last kill info.
1377 if (LocInfo.PopEpoch != PopEpoch) {
1378 LocInfo.PopEpoch = PopEpoch;
1379 LocInfo.StackEpoch = StackEpoch;
1380 // If the lower bound was in something that no longer dominates us, we
1381 // have to reset it.
1382 // We can't simply track stack size, because the stack may have had
1383 // pushes/pops in the meantime.
1384 // XXX: This is non-optimal, but only is slower cases with heavily
1385 // branching dominator trees. To get the optimal number of queries would
1386 // be to make lowerbound and lastkill a per-loc stack, and pop it until
1387 // the top of that stack dominates us. This does not seem worth it ATM.
1388 // A much cheaper optimization would be to always explore the deepest
1389 // branch of the dominator tree first. This will guarantee this resets on
1390 // the smallest set of blocks.
1391 if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
1392 !DT->dominates(LocInfo.LowerBoundBlock, BB)) {
1393 // Reset the lower bound of things to check.
1394 // TODO: Some day we should be able to reset to last kill, rather than
1395 // 0.
1396 LocInfo.LowerBound = 0;
1397 LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
1398 LocInfo.LastKillValid = false;
1399 }
1400 } else if (LocInfo.StackEpoch != StackEpoch) {
1401 // If all that has changed is the StackEpoch, we only have to check the
1402 // new things on the stack, because we've checked everything before. In
1403 // this case, the lower bound of things to check remains the same.
1404 LocInfo.PopEpoch = PopEpoch;
1405 LocInfo.StackEpoch = StackEpoch;
1406 }
1407 if (!LocInfo.LastKillValid) {
1408 LocInfo.LastKill = VersionStack.size() - 1;
1409 LocInfo.LastKillValid = true;
1410 }
1411
1412 // At this point, we should have corrected last kill and LowerBound to be
1413 // in bounds.
1414 assert(LocInfo.LowerBound < VersionStack.size() &&
1415 "Lower bound out of range");
1416 assert(LocInfo.LastKill < VersionStack.size() &&
1417 "Last kill info out of range");
1418 // In any case, the new upper bound is the top of the stack.
1419 unsigned long UpperBound = VersionStack.size() - 1;
1420
1421 if (UpperBound - LocInfo.LowerBound > MSSA->Opts.memssa_check_limit) {
1422 LLVM_DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
1423 << *(MU->getMemoryInst()) << ")"
1424 << " because there are "
1425 << UpperBound - LocInfo.LowerBound
1426 << " stores to disambiguate\n");
1427 // Because we did not walk, LastKill is no longer valid, as this may
1428 // have been a kill.
1429 LocInfo.LastKillValid = false;
1430 continue;
1431 }
1432 bool FoundClobberResult = false;
1433 unsigned UpwardWalkLimit = MSSA->Opts.memssa_check_limit;
1434 while (UpperBound > LocInfo.LowerBound) {
1435 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1436 // For phis, use the walker, see where we ended up, go there.
1437 // The invariant.group handling in MemorySSA is ad-hoc and doesn't
1438 // support updates, so don't use it to optimize uses.
1439 MemoryAccess *Result =
1440 Walker->getClobberingMemoryAccessWithoutInvariantGroup(
1441 MU, *AA, UpwardWalkLimit);
1442 // We are guaranteed to find it or something is wrong.
1443 while (VersionStack[UpperBound] != Result) {
1444 assert(UpperBound != 0);
1445 --UpperBound;
1446 }
1447 FoundClobberResult = true;
1448 break;
1449 }
1450
1451 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
1452 if (instructionClobbersQuery(MD, MU, UseMLOC, *AA)) {
1453 FoundClobberResult = true;
1454 break;
1455 }
1456 --UpperBound;
1457 }
1458
1459 // At the end of this loop, UpperBound is either a clobber, or lower bound
1460 // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1461 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
1462 MU->setDefiningAccess(VersionStack[UpperBound], true);
1463 LocInfo.LastKill = UpperBound;
1464 } else {
1465 // Otherwise, we checked all the new ones, and now we know we can get to
1466 // LastKill.
1467 MU->setDefiningAccess(VersionStack[LocInfo.LastKill], true);
1468 }
1469 LocInfo.LowerBound = VersionStack.size() - 1;
1470 LocInfo.LowerBoundBlock = BB;
1471 }
1472}
1473
1474/// Optimize uses to point to their actual clobbering definitions.
1478 VersionStack.push_back(MSSA->getLiveOnEntryDef());
1479
1480 unsigned long StackEpoch = 1;
1481 unsigned long PopEpoch = 1;
1482 // We perform a non-recursive top-down dominator tree walk.
1483 for (const auto *DomNode : depth_first(DT->getRootNode()))
1484 optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1485 LocStackInfo);
1486}
1487
1488void MemorySSA::placePHINodes(
1489 const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks) {
1490 // Determine where our MemoryPhi's should go
1491 ForwardIDFCalculator IDFs(*DT);
1492 IDFs.setDefiningBlocks(DefiningBlocks);
1494 IDFs.calculate(IDFBlocks);
1495
1496 // Now place MemoryPhi nodes.
1497 for (auto &BB : IDFBlocks)
1498 createMemoryPhi(BB);
1499}
1500
1501template <typename IterT>
1502void MemorySSA::buildMemorySSA(BatchAAResults &BAA, IterT Blocks) {
1503 // We create an access to represent "live on entry", for things like
1504 // arguments or users of globals, where the memory they use is defined before
1505 // the beginning of the function. We do not actually insert it into the IR.
1506 // We do not define a live on exit for the immediate uses, and thus our
1507 // semantics do *not* imply that something with no immediate uses can simply
1508 // be removed.
1509 BasicBlock &StartingPoint = *Blocks.begin();
1510 LiveOnEntryDef.reset(new MemoryDef(StartingPoint.getContext(), nullptr,
1511 nullptr, &StartingPoint, NextID++));
1512
1513 // We maintain lists of memory accesses per-block, trading memory for time. We
1514 // could just look up the memory access for every possible instruction in the
1515 // stream.
1516 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
1517 // Go through each block, figure out where defs occur, and chain together all
1518 // the accesses.
1519 for (BasicBlock &B : Blocks) {
1520 bool InsertIntoDef = false;
1521 AccessList *Accesses = nullptr;
1522 DefsList *Defs = nullptr;
1523 for (Instruction &I : B) {
1524 MemoryUseOrDef *MUD = createNewAccess(&I, &BAA);
1525 if (!MUD)
1526 continue;
1527
1528 if (!Accesses)
1529 Accesses = getOrCreateAccessList(&B);
1530 Accesses->push_back(MUD);
1531 if (isa<MemoryDef>(MUD)) {
1532 InsertIntoDef = true;
1533 if (!Defs)
1534 Defs = getOrCreateDefsList(&B);
1535 Defs->push_back(*MUD);
1536 }
1537 }
1538 if (InsertIntoDef)
1539 DefiningBlocks.insert(&B);
1540 }
1541 placePHINodes(DefiningBlocks);
1542
1543 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1544 // filled in with all blocks.
1545 SmallPtrSet<BasicBlock *, 16> Visited;
1546 if (L) {
1547 // Only building MemorySSA for a single loop. placePHINodes may have
1548 // inserted a MemoryPhi in the loop's preheader. As this is outside the
1549 // scope of the loop, set them to LiveOnEntry.
1550 if (auto *P = getMemoryAccess(L->getLoopPreheader())) {
1551 for (Use &U : make_early_inc_range(P->uses()))
1552 U.set(LiveOnEntryDef.get());
1554 }
1555 // Now rename accesses in the loop. Populate Visited with the exit blocks of
1556 // the loop, to limit the scope of the renaming.
1557 SmallVector<BasicBlock *> ExitBlocks;
1558 L->getExitBlocks(ExitBlocks);
1559 Visited.insert_range(ExitBlocks);
1560 renamePass(DT->getNode(L->getLoopPreheader()), LiveOnEntryDef.get(),
1561 Visited);
1562 } else {
1563 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1564 }
1565
1566 // Mark the uses in unreachable blocks as live on entry, so that they go
1567 // somewhere.
1568 for (auto &BB : Blocks)
1569 if (!Visited.count(&BB))
1570 markUnreachableAsLiveOnEntry(&BB);
1571}
1572
1573MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1574
1575MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {
1576 if (Walker)
1577 return Walker.get();
1578
1579 if (!WalkerBase)
1580 WalkerBase = std::make_unique<ClobberWalkerBase>(this, DT);
1581
1582 Walker = std::make_unique<CachingWalker>(this, WalkerBase.get());
1583 return Walker.get();
1584}
1585
1587 if (SkipWalker)
1588 return SkipWalker.get();
1589
1590 if (!WalkerBase)
1591 WalkerBase = std::make_unique<ClobberWalkerBase>(this, DT);
1592
1593 SkipWalker = std::make_unique<SkipSelfWalker>(this, WalkerBase.get());
1594 return SkipWalker.get();
1595 }
1596
1597
1598// This is a helper function used by the creation routines. It places NewAccess
1599// into the access and defs lists for a given basic block, at the given
1600// insertion point.
1602 const BasicBlock *BB,
1603 InsertionPlace Point) {
1604 auto *Accesses = getOrCreateAccessList(BB);
1605 if (Point == Beginning) {
1606 // If it's a phi node, it goes first, otherwise, it goes after any phi
1607 // nodes.
1608 if (isa<MemoryPhi>(NewAccess)) {
1609 Accesses->push_front(NewAccess);
1610 auto *Defs = getOrCreateDefsList(BB);
1611 Defs->push_front(*NewAccess);
1612 } else {
1613 auto AI = find_if_not(
1614 *Accesses, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1615 Accesses->insert(AI, NewAccess);
1616 if (!isa<MemoryUse>(NewAccess)) {
1617 auto *Defs = getOrCreateDefsList(BB);
1618 auto DI = find_if_not(
1619 *Defs, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1620 Defs->insert(DI, *NewAccess);
1621 }
1622 }
1623 } else {
1624 Accesses->push_back(NewAccess);
1625 if (!isa<MemoryUse>(NewAccess)) {
1626 auto *Defs = getOrCreateDefsList(BB);
1627 Defs->push_back(*NewAccess);
1628 }
1629 }
1630 BlockNumberingValid.erase(BB);
1631}
1632
1634 AccessList::iterator InsertPt) {
1635 auto *Accesses = getBlockAccesses(BB);
1636 bool WasEnd = InsertPt == Accesses->end();
1637 Accesses->insert(AccessList::iterator(InsertPt), What);
1638 if (!isa<MemoryUse>(What)) {
1639 auto *Defs = getOrCreateDefsList(BB);
1640 // If we got asked to insert at the end, we have an easy job, just shove it
1641 // at the end. If we got asked to insert before an existing def, we also get
1642 // an iterator. If we got asked to insert before a use, we have to hunt for
1643 // the next def.
1644 if (WasEnd) {
1645 Defs->push_back(*What);
1646 } else if (isa<MemoryDef>(InsertPt)) {
1647 Defs->insert(InsertPt->getDefsIterator(), *What);
1648 } else {
1649 while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt))
1650 ++InsertPt;
1651 // Either we found a def, or we are inserting at the end
1652 if (InsertPt == Accesses->end())
1653 Defs->push_back(*What);
1654 else
1655 Defs->insert(InsertPt->getDefsIterator(), *What);
1656 }
1657 }
1658 BlockNumberingValid.erase(BB);
1659}
1660
1661void MemorySSA::prepareForMoveTo(MemoryAccess *What, BasicBlock *BB) {
1662 // Keep it in the lookup tables, remove from the lists
1663 removeFromLists(What, false);
1664
1665 // Note that moving should implicitly invalidate the optimized state of a
1666 // MemoryUse (and Phis can't be optimized). However, it doesn't do so for a
1667 // MemoryDef.
1668 if (auto *MD = dyn_cast<MemoryDef>(What))
1669 MD->resetOptimized();
1670 What->setBlock(BB);
1671}
1672
1673// Move What before Where in the IR. The end result is that What will belong to
1674// the right lists and have the right Block set, but will not otherwise be
1675// correct. It will not have the right defining access, and if it is a def,
1676// things below it will not properly be updated.
1678 AccessList::iterator Where) {
1679 prepareForMoveTo(What, BB);
1680 insertIntoListsBefore(What, BB, Where);
1681}
1682
1684 InsertionPlace Point) {
1685 if (isa<MemoryPhi>(What)) {
1686 assert(Point == Beginning &&
1687 "Can only move a Phi at the beginning of the block");
1688 // Update lookup table entry
1689 ValueToMemoryAccess.erase(What->getBlock());
1690 bool Inserted = ValueToMemoryAccess.insert({BB, What}).second;
1691 (void)Inserted;
1692 assert(Inserted && "Cannot move a Phi to a block that already has one");
1693 }
1694
1695 prepareForMoveTo(What, BB);
1696 insertIntoListsForBlock(What, BB, Point);
1697}
1698
1699MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1700 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
1701 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
1702 // Phi's always are placed at the front of the block.
1704 ValueToMemoryAccess[BB] = Phi;
1705 return Phi;
1706}
1707
1709 MemoryAccess *Definition,
1710 const MemoryUseOrDef *Template,
1711 bool CreationMustSucceed) {
1712 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1713 MemoryUseOrDef *NewAccess = createNewAccess(I, AA, Template);
1714 if (CreationMustSucceed)
1715 assert(NewAccess != nullptr && "Tried to create a memory access for a "
1716 "non-memory touching instruction");
1717 if (NewAccess) {
1718 assert((!Definition || !isa<MemoryUse>(Definition)) &&
1719 "A use cannot be a defining access");
1720 NewAccess->setDefiningAccess(Definition);
1721 }
1722 return NewAccess;
1723}
1724
1725// Return true if the instruction has ordering constraints.
1726// Note specifically that this only considers stores and loads
1727// because others are still considered ModRef by getModRefInfo.
1728static inline bool isOrdered(const Instruction *I) {
1729 if (auto *SI = dyn_cast<StoreInst>(I)) {
1730 if (!SI->isUnordered())
1731 return true;
1732 } else if (auto *LI = dyn_cast<LoadInst>(I)) {
1733 if (!LI->isUnordered())
1734 return true;
1735 }
1736 return false;
1737}
1738
1739/// Helper function to create new memory accesses
1740template <typename AliasAnalysisType>
1741MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I,
1742 AliasAnalysisType *AAP,
1743 const MemoryUseOrDef *Template) {
1744 // The assume intrinsic has a control dependency which we model by claiming
1745 // that it writes arbitrarily. Debuginfo intrinsics may be considered
1746 // clobbers when we have a nonstandard AA pipeline. Ignore these fake memory
1747 // dependencies here.
1748 // FIXME: Replace this special casing with a more accurate modelling of
1749 // assume's control dependency.
1750 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1751 switch (II->getIntrinsicID()) {
1752 default:
1753 break;
1754 case Intrinsic::allow_runtime_check:
1755 case Intrinsic::allow_ubsan_check:
1756 case Intrinsic::assume:
1757 case Intrinsic::experimental_noalias_scope_decl:
1758 case Intrinsic::pseudoprobe:
1759 return nullptr;
1760 }
1761 }
1762
1763 // Using a nonstandard AA pipelines might leave us with unexpected modref
1764 // results for I, so add a check to not model instructions that may not read
1765 // from or write to memory. This is necessary for correctness.
1766 if (!I->mayReadFromMemory() && !I->mayWriteToMemory())
1767 return nullptr;
1768
1769 bool Def, Use;
1770 if (Template) {
1773#if !defined(NDEBUG)
1774 ModRefInfo ModRef = AAP->getModRefInfo(I, std::nullopt);
1775 bool DefCheck, UseCheck;
1776 DefCheck = isModSet(ModRef) || isOrdered(I);
1777 UseCheck = isRefSet(ModRef);
1778 // Memory accesses should only be reduced and can not be increased since AA
1779 // just might return better results as a result of some transformations.
1780 assert((Def == DefCheck || !DefCheck) &&
1781 "Memory accesses should only be reduced");
1782 if (!Def && Use != UseCheck) {
1783 // New Access should not have more power than template access
1784 assert(!UseCheck && "Invalid template");
1785 }
1786#endif
1787 } else {
1788 // Find out what affect this instruction has on memory.
1789 ModRefInfo ModRef = AAP->getModRefInfo(I, std::nullopt);
1790 // The isOrdered check is used to ensure that volatiles end up as defs
1791 // (atomics end up as ModRef right now anyway). Until we separate the
1792 // ordering chain from the memory chain, this enables people to see at least
1793 // some relative ordering to volatiles. Note that getClobberingMemoryAccess
1794 // will still give an answer that bypasses other volatile loads. TODO:
1795 // Separate memory aliasing and ordering into two different chains so that
1796 // we can precisely represent both "what memory will this read/write/is
1797 // clobbered by" and "what instructions can I move this past".
1798 Def = isModSet(ModRef) || isOrdered(I);
1799 Use = isRefSet(ModRef);
1800 }
1801
1802 // It's possible for an instruction to not modify memory at all. During
1803 // construction, we ignore them.
1804 if (!Def && !Use)
1805 return nullptr;
1806
1807 MemoryUseOrDef *MUD;
1808 if (Def) {
1809 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
1810 } else {
1811 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
1813 MemoryAccess *LiveOnEntry = getLiveOnEntryDef();
1814 MUD->setOptimized(LiveOnEntry);
1815 }
1816 }
1817 ValueToMemoryAccess[I] = MUD;
1818 return MUD;
1819}
1820
1821/// Properly remove \p MA from all of MemorySSA's lookup tables.
1823 assert(MA->use_empty() &&
1824 "Trying to remove memory access that still has uses");
1825 BlockNumbering.erase(MA);
1826 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1827 MUD->setDefiningAccess(nullptr);
1828 // Invalidate our walker's cache if necessary
1829 if (!isa<MemoryUse>(MA))
1831
1832 Value *MemoryInst;
1833 if (const auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1834 MemoryInst = MUD->getMemoryInst();
1835 else
1836 MemoryInst = MA->getBlock();
1837
1838 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1839 if (VMA->second == MA)
1840 ValueToMemoryAccess.erase(VMA);
1841}
1842
1843/// Properly remove \p MA from all of MemorySSA's lists.
1844///
1845/// Because of the way the intrusive list and use lists work, it is important to
1846/// do removal in the right order.
1847/// ShouldDelete defaults to true, and will cause the memory access to also be
1848/// deleted, not just removed.
1849void MemorySSA::removeFromLists(MemoryAccess *MA, bool ShouldDelete) {
1850 BasicBlock *BB = MA->getBlock();
1851 // The access list owns the reference, so we erase it from the non-owning list
1852 // first.
1853 if (!isa<MemoryUse>(MA)) {
1854 auto DefsIt = PerBlockDefs.find(BB);
1855 std::unique_ptr<DefsList> &Defs = DefsIt->second;
1856 Defs->remove(*MA);
1857 if (Defs->empty())
1858 PerBlockDefs.erase(DefsIt);
1859 }
1860
1861 // The erase call here will delete it. If we don't want it deleted, we call
1862 // remove instead.
1863 auto AccessIt = PerBlockAccesses.find(BB);
1864 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
1865 if (ShouldDelete)
1866 Accesses->erase(MA);
1867 else
1868 Accesses->remove(MA);
1869
1870 if (Accesses->empty()) {
1871 PerBlockAccesses.erase(AccessIt);
1872 BlockNumberingValid.erase(BB);
1873 }
1874}
1875
1877 MemorySSAAnnotatedWriter Writer(this);
1878 Function *F = this->F;
1879 if (L)
1880 F = L->getHeader()->getParent();
1881 F->print(OS, &Writer);
1882}
1883
1884#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1886#endif
1887
1889#if !defined(NDEBUG) && defined(EXPENSIVE_CHECKS)
1891#endif
1892
1893#ifndef NDEBUG
1894 if (F) {
1895 auto Blocks = iterator_range(F->begin(), F->end());
1898 if (VL == VerificationLevel::Full)
1899 verifyPrevDefInPhis(Blocks);
1900 } else {
1901 assert(L && "must either have loop or function");
1902 auto Blocks =
1903 map_range(L->blocks(), [](const BasicBlock *BB) -> BasicBlock & {
1904 return *const_cast<BasicBlock *>(BB);
1905 });
1908 if (VL == VerificationLevel::Full)
1909 verifyPrevDefInPhis(Blocks);
1910 }
1911#endif
1912 // Previously, the verification used to also verify that the clobberingAccess
1913 // cached by MemorySSA is the same as the clobberingAccess found at a later
1914 // query to AA. This does not hold true in general due to the current fragility
1915 // of BasicAA which has arbitrary caps on the things it analyzes before giving
1916 // up. As a result, transformations that are correct, will lead to BasicAA
1917 // returning different Alias answers before and after that transformation.
1918 // Invalidating MemorySSA is not an option, as the results in BasicAA can be so
1919 // random, in the worst case we'd need to rebuild MemorySSA from scratch after
1920 // every transformation, which defeats the purpose of using it. For such an
1921 // example, see test4 added in D51960.
1922}
1923
1924template <typename IterT>
1925void MemorySSA::verifyPrevDefInPhis(IterT Blocks) const {
1926 for (const BasicBlock &BB : Blocks) {
1927 if (MemoryPhi *Phi = getMemoryAccess(&BB)) {
1928 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
1929 auto *Pred = Phi->getIncomingBlock(I);
1930 auto *IncAcc = Phi->getIncomingValue(I);
1931 // If Pred has no unreachable predecessors, get last def looking at
1932 // IDoms. If, while walkings IDoms, any of these has an unreachable
1933 // predecessor, then the incoming def can be any access.
1934 if (auto *DTNode = DT->getNode(Pred)) {
1935 while (DTNode) {
1936 if (auto *DefList = getBlockDefs(DTNode->getBlock())) {
1937 auto *LastAcc = &*(--DefList->end());
1938 assert(LastAcc == IncAcc &&
1939 "Incorrect incoming access into phi.");
1940 (void)IncAcc;
1941 (void)LastAcc;
1942 break;
1943 }
1944 DTNode = DTNode->getIDom();
1945 }
1946 } else {
1947 // If Pred has unreachable predecessors, but has at least a Def, the
1948 // incoming access can be the last Def in Pred, or it could have been
1949 // optimized to LoE. After an update, though, the LoE may have been
1950 // replaced by another access, so IncAcc may be any access.
1951 // If Pred has unreachable predecessors and no Defs, incoming access
1952 // should be LoE; However, after an update, it may be any access.
1953 }
1954 }
1955 }
1956 }
1957}
1958
1959/// Verify that all of the blocks we believe to have valid domination numbers
1960/// actually have valid domination numbers.
1961template <typename IterT>
1962void MemorySSA::verifyDominationNumbers(IterT Blocks) const {
1963 if (BlockNumberingValid.empty())
1964 return;
1965
1966 SmallPtrSet<const BasicBlock *, 16> ValidBlocks = BlockNumberingValid;
1967 for (const BasicBlock &BB : Blocks) {
1968 if (!ValidBlocks.count(&BB))
1969 continue;
1970
1971 ValidBlocks.erase(&BB);
1972
1973 const AccessList *Accesses = getBlockAccesses(&BB);
1974 // It's correct to say an empty block has valid numbering.
1975 if (!Accesses)
1976 continue;
1977
1978 // Block numbering starts at 1.
1979 unsigned long LastNumber = 0;
1980 for (const MemoryAccess &MA : *Accesses) {
1981 auto ThisNumberIter = BlockNumbering.find(&MA);
1982 assert(ThisNumberIter != BlockNumbering.end() &&
1983 "MemoryAccess has no domination number in a valid block!");
1984
1985 unsigned long ThisNumber = ThisNumberIter->second;
1986 assert(ThisNumber > LastNumber &&
1987 "Domination numbers should be strictly increasing!");
1988 (void)LastNumber;
1989 LastNumber = ThisNumber;
1990 }
1991 }
1992
1993 assert(ValidBlocks.empty() &&
1994 "All valid BasicBlocks should exist in F -- dangling pointers?");
1995}
1996
1997/// Verify ordering: the order and existence of MemoryAccesses matches the
1998/// order and existence of memory affecting instructions.
1999/// Verify domination: each definition dominates all of its uses.
2000/// Verify def-uses: the immediate use information - walk all the memory
2001/// accesses and verifying that, for each use, it appears in the appropriate
2002/// def's use list
2003template <typename IterT>
2005 VerificationLevel VL) const {
2006 // Walk all the blocks, comparing what the lookups think and what the access
2007 // lists think, as well as the order in the blocks vs the order in the access
2008 // lists.
2009 SmallVector<MemoryAccess *, 32> ActualAccesses;
2011 for (BasicBlock &B : Blocks) {
2012 const AccessList *AL = getBlockAccesses(&B);
2013 const auto *DL = getBlockDefs(&B);
2014 MemoryPhi *Phi = getMemoryAccess(&B);
2015 if (Phi) {
2016 // Verify ordering.
2017 ActualAccesses.push_back(Phi);
2018 ActualDefs.push_back(Phi);
2019 // Verify domination
2020 for (const Use &U : Phi->uses()) {
2021 assert(dominates(Phi, U) && "Memory PHI does not dominate it's uses");
2022 (void)U;
2023 }
2024 // Verify def-uses for full verify.
2025 if (VL == VerificationLevel::Full) {
2026 assert(Phi->getNumOperands() == pred_size(&B) &&
2027 "Incomplete MemoryPhi Node");
2028 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
2029 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
2030 assert(is_contained(predecessors(&B), Phi->getIncomingBlock(I)) &&
2031 "Incoming phi block not a block predecessor");
2032 }
2033 }
2034 }
2035
2036 for (Instruction &I : B) {
2038 assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) &&
2039 "We have memory affecting instructions "
2040 "in this block but they are not in the "
2041 "access list or defs list");
2042 if (MA) {
2043 // Verify ordering.
2044 ActualAccesses.push_back(MA);
2045 if (MemoryAccess *MD = dyn_cast<MemoryDef>(MA)) {
2046 // Verify ordering.
2047 ActualDefs.push_back(MA);
2048 // Verify domination.
2049 for (const Use &U : MD->uses()) {
2050 assert(dominates(MD, U) &&
2051 "Memory Def does not dominate it's uses");
2052 (void)U;
2053 }
2054 }
2055 // Verify def-uses for full verify.
2056 if (VL == VerificationLevel::Full)
2057 verifyUseInDefs(MA->getDefiningAccess(), MA);
2058 }
2059 }
2060 // Either we hit the assert, really have no accesses, or we have both
2061 // accesses and an access list. Same with defs.
2062 if (!AL && !DL)
2063 continue;
2064 // Verify ordering.
2065 assert(AL->size() == ActualAccesses.size() &&
2066 "We don't have the same number of accesses in the block as on the "
2067 "access list");
2068 assert((DL || ActualDefs.size() == 0) &&
2069 "Either we should have a defs list, or we should have no defs");
2070 assert((!DL || DL->size() == ActualDefs.size()) &&
2071 "We don't have the same number of defs in the block as on the "
2072 "def list");
2073 auto ALI = AL->begin();
2074 auto AAI = ActualAccesses.begin();
2075 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
2076 assert(&*ALI == *AAI && "Not the same accesses in the same order");
2077 ++ALI;
2078 ++AAI;
2079 }
2080 ActualAccesses.clear();
2081 if (DL) {
2082 auto DLI = DL->begin();
2083 auto ADI = ActualDefs.begin();
2084 while (DLI != DL->end() && ADI != ActualDefs.end()) {
2085 assert(&*DLI == *ADI && "Not the same defs in the same order");
2086 ++DLI;
2087 ++ADI;
2088 }
2089 }
2090 ActualDefs.clear();
2091 }
2092}
2093
2094/// Verify the def-use lists in MemorySSA, by verifying that \p Use
2095/// appears in the use list of \p Def.
2096void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
2097 // The live on entry use may cause us to get a NULL def here
2098 if (!Def)
2100 "Null def but use not point to live on entry def");
2101 else
2102 assert(is_contained(Def->users(), Use) &&
2103 "Did not find use in def's use list");
2104}
2105
2106/// Perform a local numbering on blocks so that instruction ordering can be
2107/// determined in constant time.
2108/// TODO: We currently just number in order. If we numbered by N, we could
2109/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
2110/// log2(N) sequences of mixed before and after) without needing to invalidate
2111/// the numbering.
2112void MemorySSA::renumberBlock(const BasicBlock *B) const {
2113 // The pre-increment ensures the numbers really start at 1.
2114 unsigned long CurrentNumber = 0;
2115 const AccessList *AL = getBlockAccesses(B);
2116 assert(AL != nullptr && "Asking to renumber an empty block");
2117 for (const auto &I : *AL)
2118 BlockNumbering[&I] = ++CurrentNumber;
2119 BlockNumberingValid.insert(B);
2120}
2121
2122/// Determine, for two memory accesses in the same block,
2123/// whether \p Dominator dominates \p Dominatee.
2124/// \returns True if \p Dominator dominates \p Dominatee.
2126 const MemoryAccess *Dominatee) const {
2127 const BasicBlock *DominatorBlock = Dominator->getBlock();
2128
2129 assert((DominatorBlock == Dominatee->getBlock()) &&
2130 "Asking for local domination when accesses are in different blocks!");
2131 // A node dominates itself.
2132 if (Dominatee == Dominator)
2133 return true;
2134
2135 // When Dominatee is defined on function entry, it is not dominated by another
2136 // memory access.
2137 if (isLiveOnEntryDef(Dominatee))
2138 return false;
2139
2140 // When Dominator is defined on function entry, it dominates the other memory
2141 // access.
2142 if (isLiveOnEntryDef(Dominator))
2143 return true;
2144
2145 if (!BlockNumberingValid.count(DominatorBlock))
2146 renumberBlock(DominatorBlock);
2147
2148 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
2149 // All numbers start with 1
2150 assert(DominatorNum != 0 && "Block was not numbered properly");
2151 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
2152 assert(DominateeNum != 0 && "Block was not numbered properly");
2153 return DominatorNum < DominateeNum;
2154}
2155
2157 const MemoryAccess *Dominatee) const {
2158 if (Dominator == Dominatee)
2159 return true;
2160
2161 if (isLiveOnEntryDef(Dominatee))
2162 return false;
2163
2164 if (Dominator->getBlock() != Dominatee->getBlock())
2165 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
2166 return locallyDominates(Dominator, Dominatee);
2167}
2168
2170 const Use &Dominatee) const {
2171 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
2172 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
2173 // The def must dominate the incoming block of the phi.
2174 if (UseBB != Dominator->getBlock())
2175 return DT->dominates(Dominator->getBlock(), UseBB);
2176 // If the UseBB and the DefBB are the same, compare locally.
2177 return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
2178 }
2179 // If it's not a PHI node use, the normal dominates can already handle it.
2180 return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
2181}
2182
2184 if (IsOptimized)
2185 return;
2186
2187 BatchAAResults BatchAA(*AA);
2188 ClobberWalkerBase WalkerBase(this, DT);
2189 CachingWalker WalkerLocal(this, &WalkerBase);
2190 OptimizeUses(this, &WalkerLocal, &BatchAA, DT).optimizeUses();
2191 IsOptimized = true;
2192}
2193
2195 switch (getValueID()) {
2196 case MemoryPhiVal: return static_cast<const MemoryPhi *>(this)->print(OS);
2197 case MemoryDefVal: return static_cast<const MemoryDef *>(this)->print(OS);
2198 case MemoryUseVal: return static_cast<const MemoryUse *>(this)->print(OS);
2199 }
2200 llvm_unreachable("invalid value id");
2201}
2202
2205
2206 auto printID = [&OS](MemoryAccess *A) {
2207 if (A && A->getID())
2208 OS << A->getID();
2209 else
2210 OS << LiveOnEntryStr;
2211 };
2212
2213 OS << getID() << " = MemoryDef(";
2214 printID(UO);
2215 OS << ")";
2216
2217 if (isOptimized()) {
2218 OS << "->";
2219 printID(getOptimized());
2220 }
2221}
2222
2224 ListSeparator LS(",");
2225 OS << getID() << " = MemoryPhi(";
2226 for (const auto &Op : operands()) {
2229
2230 OS << LS << '{';
2231 if (BB->hasName())
2232 OS << BB->getName();
2233 else
2234 BB->printAsOperand(OS, false);
2235 OS << ',';
2236 if (unsigned ID = MA->getID())
2237 OS << ID;
2238 else
2239 OS << LiveOnEntryStr;
2240 OS << '}';
2241 }
2242 OS << ')';
2243}
2244
2247 OS << "MemoryUse(";
2248 if (UO && UO->getID())
2249 OS << UO->getID();
2250 else
2251 OS << LiveOnEntryStr;
2252 OS << ')';
2253}
2254
2256// Cannot completely remove virtual function even in release mode.
2257#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2258 print(dbgs());
2259 dbgs() << "\n";
2260#endif
2261}
2262
2264private:
2265 const Function &F;
2266 MemorySSAAnnotatedWriter MSSAWriter;
2267
2268public:
2270 : F(F), MSSAWriter(&MSSA) {}
2271
2272 const Function *getFunction() { return &F; }
2273 MemorySSAAnnotatedWriter &getWriter() { return MSSAWriter; }
2274};
2275
2276namespace llvm {
2277
2278template <>
2281 return &(CFGInfo->getFunction()->getEntryBlock());
2282 }
2283
2284 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
2286
2288 return nodes_iterator(CFGInfo->getFunction()->begin());
2289 }
2290
2292 return nodes_iterator(CFGInfo->getFunction()->end());
2293 }
2294
2295 static size_t size(DOTFuncMSSAInfo *CFGInfo) {
2296 return CFGInfo->getFunction()->size();
2297 }
2298};
2299
2300template <>
2302
2303 DOTGraphTraits(bool IsSimple = false) : DefaultDOTGraphTraits(IsSimple) {}
2304
2305 static std::string getGraphName(DOTFuncMSSAInfo *CFGInfo) {
2306 return "MSSA CFG for '" + CFGInfo->getFunction()->getName().str() +
2307 "' function";
2308 }
2309
2310 std::string getNodeLabel(const BasicBlock *Node, DOTFuncMSSAInfo *CFGInfo) {
2312 Node, nullptr,
2313 [CFGInfo](raw_string_ostream &OS, const BasicBlock &BB) -> void {
2314 BB.print(OS, &CFGInfo->getWriter(), true, true);
2315 },
2316 [](std::string &S, unsigned &I, unsigned Idx) -> void {
2317 std::string Str = S.substr(I, Idx - I);
2318 StringRef SR = Str;
2319 if (SR.count(" = MemoryDef(") || SR.count(" = MemoryPhi(") ||
2320 SR.count("MemoryUse("))
2321 return;
2323 });
2324 }
2325
2330
2331 /// Display the raw branch weights from PGO.
2333 DOTFuncMSSAInfo *CFGInfo) {
2334 return "";
2335 }
2336
2338 DOTFuncMSSAInfo *CFGInfo) {
2339 return getNodeLabel(Node, CFGInfo).find(';') != std::string::npos
2340 ? "style=filled, fillcolor=lightpink"
2341 : "";
2342 }
2343};
2344
2345} // namespace llvm
2346
2347AnalysisKey MemorySSAAnalysis::Key;
2348
2351 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2352 auto &AA = AM.getResult<AAManager>(F);
2353 return MemorySSAAnalysis::Result(std::make_unique<MemorySSA>(F, &AA, &DT));
2354}
2355
2357 Function &F, const PreservedAnalyses &PA,
2358 FunctionAnalysisManager::Invalidator &Inv) {
2359 auto PAC = PA.getChecker<MemorySSAAnalysis>();
2360 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
2361 Inv.invalidate<AAManager>(F, PA) ||
2362 Inv.invalidate<DominatorTreeAnalysis>(F, PA);
2363}
2364
2367 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
2368 if (EnsureOptimizedUses)
2369 MSSA.ensureOptimizedUses();
2370 StringRef DotCFGMSSA = getAnalysisOptions(F).dot_cfg_mssa;
2371 if (!DotCFGMSSA.empty()) {
2372 DOTFuncMSSAInfo CFGInfo(F, MSSA);
2373 WriteGraph(&CFGInfo, "", false, "MSSA", DotCFGMSSA.str());
2374 } else {
2375 OS << "MemorySSA for function: " << F.getName() << "\n";
2376 MSSA.print(OS);
2377 }
2378
2379 return PreservedAnalyses::all();
2380}
2381
2384 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
2385 OS << "MemorySSA (walker) for function: " << F.getName() << "\n";
2386 MemorySSAWalkerAnnotatedWriter Writer(&MSSA);
2387 F.print(OS, &Writer);
2388
2389 return PreservedAnalyses::all();
2390}
2391
2394 AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA();
2395
2396 return PreservedAnalyses::all();
2397}
2398
2400
2402
2404
2410
2412 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2413 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2414 MSSA.reset(new MemorySSA(F, &AA, &DT));
2415 return false;
2416}
2417
2419 if (VerifyMemorySSA)
2420 MSSA->verifyMemorySSA();
2421}
2422
2424 MSSA->print(OS);
2425}
2426
2428
2429/// Walk the use-def chains starting at \p StartingAccess and find
2430/// the MemoryAccess that actually clobbers Loc.
2431///
2432/// \returns our clobbering memory access
2434 MemoryAccess *StartingAccess, const MemoryLocation &Loc,
2435 BatchAAResults &BAA, unsigned &UpwardWalkLimit) {
2436 assert(!isa<MemoryUse>(StartingAccess) && "Use cannot be defining access");
2437
2438 // If location is undefined, conservatively return starting access.
2439 if (Loc.Ptr == nullptr)
2440 return StartingAccess;
2441
2442 Instruction *I = nullptr;
2443 if (auto *StartingUseOrDef = dyn_cast<MemoryUseOrDef>(StartingAccess)) {
2444 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
2445 return StartingUseOrDef;
2446
2447 I = StartingUseOrDef->getMemoryInst();
2448
2449 // Conservatively, fences are always clobbers, so don't perform the walk if
2450 // we hit a fence.
2451 if (!isa<CallBase>(I) && I->isFenceLike())
2452 return StartingUseOrDef;
2453 }
2454
2455 UpwardsMemoryQuery Q;
2456 Q.OriginalAccess = StartingAccess;
2457 Q.StartingLoc = Loc;
2458 Q.Inst = nullptr;
2459 Q.IsCall = false;
2460
2461 // Unlike the other function, do not walk to the def of a def, because we are
2462 // handed something we already believe is the clobbering access.
2463 // We never set SkipSelf to true in Q in this method.
2464 MemoryAccess *Clobber =
2465 Walker.findClobber(BAA, StartingAccess, Q, UpwardWalkLimit);
2466 LLVM_DEBUG({
2467 dbgs() << "Clobber starting at access " << *StartingAccess << "\n";
2468 if (I)
2469 dbgs() << " for instruction " << *I << "\n";
2470 dbgs() << " is " << *Clobber << "\n";
2471 });
2472 return Clobber;
2473}
2474
2475static const Instruction *
2477 if (!I.hasMetadata(LLVMContext::MD_invariant_group) || I.isVolatile())
2478 return nullptr;
2479
2480 // We consider bitcasts and zero GEPs to be the same pointer value. Start by
2481 // stripping bitcasts and zero GEPs, then we will recursively look at loads
2482 // and stores through bitcasts and zero GEPs.
2483 Value *PointerOperand = getLoadStorePointerOperand(&I)->stripPointerCasts();
2484
2485 // It's not safe to walk the use list of a global value because function
2486 // passes aren't allowed to look outside their functions.
2487 // FIXME: this could be fixed by filtering instructions from outside of
2488 // current function.
2489 if (isa<Constant>(PointerOperand))
2490 return nullptr;
2491
2492 const Instruction *MostDominatingInstruction = &I;
2493
2494 for (const User *Us : PointerOperand->users()) {
2495 auto *U = dyn_cast<Instruction>(Us);
2496 if (!U || U == &I || !DT.dominates(U, MostDominatingInstruction))
2497 continue;
2498
2499 // If we hit a load/store with an invariant.group metadata and the same
2500 // pointer operand, we can assume that value pointed to by the pointer
2501 // operand didn't change.
2502 if (U->hasMetadata(LLVMContext::MD_invariant_group) &&
2503 getLoadStorePointerOperand(U) == PointerOperand && !U->isVolatile()) {
2504 MostDominatingInstruction = U;
2505 }
2506 }
2507
2508 return MostDominatingInstruction == &I ? nullptr : MostDominatingInstruction;
2509}
2510
2512 MemoryAccess *MA, BatchAAResults &BAA, unsigned &UpwardWalkLimit,
2513 bool SkipSelf, bool UseInvariantGroup) {
2514 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2515 // If this is a MemoryPhi, we can't do anything.
2516 if (!StartingAccess)
2517 return MA;
2518
2519 if (UseInvariantGroup) {
2521 *StartingAccess->getMemoryInst(), MSSA->getDomTree())) {
2523
2524 auto *ClobberMA = MSSA->getMemoryAccess(I);
2525 assert(ClobberMA);
2526 if (isa<MemoryUse>(ClobberMA))
2527 return ClobberMA->getDefiningAccess();
2528 return ClobberMA;
2529 }
2530 }
2531
2532 bool IsOptimized = false;
2533
2534 // If this is an already optimized use or def, return the optimized result.
2535 // Note: Currently, we store the optimized def result in a separate field,
2536 // since we can't use the defining access.
2537 if (StartingAccess->isOptimized()) {
2538 if (!SkipSelf || !isa<MemoryDef>(StartingAccess))
2539 return StartingAccess->getOptimized();
2540 IsOptimized = true;
2541 }
2542
2543 const Instruction *I = StartingAccess->getMemoryInst();
2544 // We can't sanely do anything with a fence, since they conservatively clobber
2545 // all memory, and have no locations to get pointers from to try to
2546 // disambiguate.
2547 if (!isa<CallBase>(I) && I->isFenceLike())
2548 return StartingAccess;
2549
2550 UpwardsMemoryQuery Q(I, StartingAccess);
2551
2553 MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
2554 StartingAccess->setOptimized(LiveOnEntry);
2555 return LiveOnEntry;
2556 }
2557
2558 MemoryAccess *OptimizedAccess;
2559 if (!IsOptimized) {
2560 // Start with the thing we already think clobbers this location
2561 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2562
2563 // At this point, DefiningAccess may be the live on entry def.
2564 // If it is, we will not get a better result.
2565 if (MSSA->isLiveOnEntryDef(DefiningAccess)) {
2566 StartingAccess->setOptimized(DefiningAccess);
2567 return DefiningAccess;
2568 }
2569
2570 OptimizedAccess =
2571 Walker.findClobber(BAA, DefiningAccess, Q, UpwardWalkLimit);
2572 StartingAccess->setOptimized(OptimizedAccess);
2573 } else
2574 OptimizedAccess = StartingAccess->getOptimized();
2575
2576 LLVM_DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2577 LLVM_DEBUG(dbgs() << *StartingAccess << "\n");
2578 LLVM_DEBUG(dbgs() << "Optimized Memory SSA clobber for " << *I << " is ");
2579 LLVM_DEBUG(dbgs() << *OptimizedAccess << "\n");
2580
2581 MemoryAccess *Result;
2582 if (SkipSelf && isa<MemoryPhi>(OptimizedAccess) &&
2583 isa<MemoryDef>(StartingAccess) && UpwardWalkLimit) {
2584 assert(isa<MemoryDef>(Q.OriginalAccess));
2585 Q.SkipSelfAccess = true;
2586 Result = Walker.findClobber(BAA, OptimizedAccess, Q, UpwardWalkLimit);
2587 } else
2588 Result = OptimizedAccess;
2589
2590 LLVM_DEBUG(dbgs() << "Result Memory SSA clobber [SkipSelf = " << SkipSelf);
2591 LLVM_DEBUG(dbgs() << "] for " << *I << " is " << *Result << "\n");
2592
2593 return Result;
2594}
2595
2596MemoryAccess *
2598 BatchAAResults &) {
2599 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2600 return Use->getDefiningAccess();
2601 return MA;
2602}
2603
2605 MemoryAccess *StartingAccess, const MemoryLocation &, BatchAAResults &) {
2606 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2607 return Use->getDefiningAccess();
2608 return StartingAccess;
2609}
2610
2611void MemoryPhi::deleteMe(DerivedUser *Self) {
2612 delete static_cast<MemoryPhi *>(Self);
2613}
2614
2615void MemoryDef::deleteMe(DerivedUser *Self) {
2616 delete static_cast<MemoryDef *>(Self);
2617}
2618
2619void MemoryUse::deleteMe(DerivedUser *Self) {
2620 delete static_cast<MemoryUse *>(Self);
2621}
2622
2623bool upward_defs_iterator::IsGuaranteedLoopInvariant(const Value *Ptr) const {
2624 auto IsGuaranteedLoopInvariantBase = [](const Value *Ptr) {
2625 Ptr = Ptr->stripPointerCasts();
2626 if (!isa<Instruction>(Ptr))
2627 return true;
2628 return isa<AllocaInst>(Ptr);
2629 };
2630
2631 Ptr = Ptr->stripPointerCasts();
2632 if (auto *I = dyn_cast<Instruction>(Ptr)) {
2633 if (I->getParent()->isEntryBlock())
2634 return true;
2635 }
2636 if (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
2637 return IsGuaranteedLoopInvariantBase(GEP->getPointerOperand()) &&
2638 GEP->hasAllConstantIndices();
2639 }
2640 return IsGuaranteedLoopInvariantBase(Ptr);
2641}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Atomic ordering constants.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:690
DXIL Forward Handle Accesses
DXIL Resource Access
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
early cse Early CSE w MemorySSA
Hexagon Common GEP
#define _
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file provides utility analysis objects describing memory locations.
static bool instructionClobbersQuery(const MemoryDef *MD, const MemoryLocation &UseLoc, const Instruction *UseInst, AliasAnalysisType &AA)
static void checkClobberSanity(MemoryAccess *Start, MemoryAccess *ClobberAt, const MemoryLocation &StartLoc, const MemorySSA &MSSA, const UpwardsMemoryQuery &Query, BatchAAResults &AA, bool AllowImpreciseClobber=false)
Verifies that Start is clobbered by ClobberAt, and that nothing inbetween Start and ClobberAt can clo...
static cl::opt< bool, true > VerifyMemorySSAX("verify-memoryssa", cl::location(VerifyMemorySSA), cl::Hidden, cl::desc("Enable verification of MemorySSA."))
static const char LiveOnEntryStr[]
Definition MemorySSA.cpp:83
static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysisType &AA, const Instruction *I)
static bool areLoadsReorderable(const LoadInst *Use, const LoadInst *MayClobber)
This does one-way checks to see if Use could theoretically be hoisted above MayClobber.
static const Instruction * getInvariantGroupClobberingInstruction(Instruction &I, DominatorTree &DT)
static bool isOrdered(const Instruction *I)
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
#define T
static std::string getNodeLabel(const ValueInfo &VI, GlobalValueSummary *GVS)
uint64_t IntrinsicInst * II
#define P(N)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
DOTFuncMSSAInfo(const Function &F, MemorySSA &MSSA)
const Function * getFunction()
MemorySSAAnnotatedWriter & getWriter()
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI BasicBlock::iterator erase(BasicBlock::iterator FromIt, BasicBlock::iterator ToIt)
Erases a range of instructions from FromIt to (not including) ToIt.
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
LLVM_ABI void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW=nullptr, bool ShouldPreserveUseListOrder=false, bool IsForDebug=false) const
Print the basic block to an output stream with an optional AssemblyAnnotationWriter.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
Temporarily set the cross iteration mode on a BatchAA instance.
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
Value * getCalledOperand() const
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
unsigned arg_size() const
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Extension point for the Value hierarchy.
Definition DerivedUser.h:27
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *, BatchAAResults &) override
Does the same thing as getClobberingMemoryAccess(const Instruction *I), but takes a MemoryAccess inst...
iterator begin() const
NodeT * getBlock() const
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
FunctionPass(char &pid)
Definition Pass.h:314
iterator begin()
Definition Function.h:838
size_t size() const
Definition Function.h:843
iterator end()
Definition Function.h:840
Module * getParent()
Get the module that this global value is contained inside of...
A wrapper class for inspecting calls to intrinsic functions.
A helper class to return the specified delimiter string after the first invocation of operator String...
An instruction for reading from memory.
bool isVolatile() const
Return true if this is a load from a volatile memory location.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
LLVM_ABI void dump() const
MemoryAccess(const MemoryAccess &)=delete
friend class MemoryUse
Definition MemorySSA.h:211
friend class MemoryPhi
Definition MemorySSA.h:209
friend class MemoryDef
Definition MemorySSA.h:208
BasicBlock * getBlock() const
Definition MemorySSA.h:163
LLVM_ABI void print(raw_ostream &OS) const
unsigned getID() const
Used for debugging and tracking things about MemoryAccesses.
Definition MemorySSA.h:657
void setBlock(BasicBlock *BB)
Used by MemorySSA to change the block of a MemoryAccess when it is moved.
Definition MemorySSA.h:216
Represents a read-write access to memory, whether it is a must-alias, or a may-alias.
Definition MemorySSA.h:372
LLVM_ABI void print(raw_ostream &OS) const
void resetOptimized()
Definition MemorySSA.h:406
MemoryAccess * getOptimized() const
Definition MemorySSA.h:398
unsigned getID() const
Definition MemorySSA.h:413
bool isOptimized() const
Definition MemorySSA.h:402
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
Represents phi nodes for memory accesses.
Definition MemorySSA.h:480
BasicBlock * getIncomingBlock(unsigned I) const
Return incoming basic block number i.
Definition MemorySSA.h:543
LLVM_ABI void print(raw_ostream &OS) const
unsigned getID() const
Definition MemorySSA.h:628
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:917
LLVM_ABI Result run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
static LLVM_ABI bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU, AliasAnalysis &AA)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
This is the generic walker interface for walkers of MemorySSA.
Definition MemorySSA.h:1001
friend class MemorySSA
Definition MemorySSA.h:1081
MemoryAccess * getClobberingMemoryAccess(const Instruction *I, BatchAAResults &AA)
Given a memory Mod/Ref/ModRef'ing instruction, calling this will give you the nearest dominating Memo...
Definition MemorySSA.h:1030
LLVM_ABI MemorySSAWalker(MemorySSA *)
virtual void invalidateInfo(MemoryAccess *)
Given a memory access, invalidate anything this walker knows about that access.
Definition MemorySSA.h:1078
Legacy analysis pass which computes MemorySSA.
Definition MemorySSA.h:970
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
bool runOnFunction(Function &) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void print(raw_ostream &OS, const Module *M=nullptr) const override
print - Print out the internal state of the pass.
A MemorySSAWalker that does AA walks to disambiguate accesses.
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, BatchAAResults &BAA) override
Does the same thing as getClobberingMemoryAccess(const Instruction *I), but takes a MemoryAccess inst...
MemoryAccess * getClobberingMemoryAccessWithoutInvariantGroup(MemoryAccess *MA, BatchAAResults &BAA, unsigned &UWL)
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, const MemoryLocation &Loc, BatchAAResults &BAA, unsigned &UWL)
void invalidateInfo(MemoryAccess *MA) override
Given a memory access, invalidate anything this walker knows about that access.
~CachingWalker() override=default
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, BatchAAResults &BAA, unsigned &UWL)
CachingWalker(MemorySSA *M, ClobberWalkerBase *W)
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, const MemoryLocation &Loc, BatchAAResults &BAA) override
Given a potentially clobbering memory access and a new location, calling this will give you the neare...
ClobberWalkerBase(MemorySSA *M, DominatorTree *D)
MemoryAccess * getClobberingMemoryAccessBase(MemoryAccess *, BatchAAResults &, unsigned &, bool, bool UseInvariantGroup=true)
MemoryAccess * getClobberingMemoryAccessBase(MemoryAccess *, const MemoryLocation &, BatchAAResults &, unsigned &)
This class is a batch walker of all MemoryUse's in the program, and points their defining access at t...
void optimizeUses()
Optimize uses to point to their actual clobbering definitions.
OptimizeUses(MemorySSA *MSSA, CachingWalker *Walker, BatchAAResults *BAA, DominatorTree *DT)
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, const MemoryLocation &Loc, BatchAAResults &BAA) override
Given a potentially clobbering memory access and a new location, calling this will give you the neare...
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, const MemoryLocation &Loc, BatchAAResults &BAA, unsigned &UWL)
~SkipSelfWalker() override=default
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, BatchAAResults &BAA, unsigned &UWL)
SkipSelfWalker(MemorySSA *M, ClobberWalkerBase *W)
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, BatchAAResults &BAA) override
Does the same thing as getClobberingMemoryAccess(const Instruction *I), but takes a MemoryAccess inst...
void invalidateInfo(MemoryAccess *MA) override
Given a memory access, invalidate anything this walker knows about that access.
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:696
LLVM_ABI void dump() const
simple_ilist< MemoryAccess, ilist_tag< MSSAHelpers::DefsOnlyTag > > DefsList
Definition MemorySSA.h:748
LLVM_ABI void moveTo(MemoryUseOrDef *What, BasicBlock *BB, AccessList::iterator Where)
void renamePass(BasicBlock *BB, MemoryAccess *IncomingVal, SmallPtrSetImpl< BasicBlock * > &Visited)
Definition MemorySSA.h:816
DefsList * getBlockDefs(const BasicBlock *BB) const
Return the list of MemoryDef's and MemoryPhi's for a given basic block.
Definition MemorySSA.h:759
LLVM_ABI MemorySSAWalker * getSkipSelfWalker()
LLVM_ABI MemorySSA(Function &, AliasAnalysis *, DominatorTree *)
iplist< MemoryAccess, ilist_tag< MSSAHelpers::AllAccessTag > > AccessList
Definition MemorySSA.h:747
AccessList * getBlockAccesses(const BasicBlock *BB) const
Return the list of MemoryAccess's for a given basic block.
Definition MemorySSA.h:752
LLVM_ABI bool dominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in potentially different blocks, determine whether MemoryAccess A dominates...
void verifyOrderingDominationAndDefUses(IterT Blocks, VerificationLevel=VerificationLevel::Fast) const
Verify ordering: the order and existence of MemoryAccesses matches the order and existence of memory ...
LLVM_ABI void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
LLVM_ABI void insertIntoListsForBlock(MemoryAccess *, const BasicBlock *, InsertionPlace)
LLVM_ABI MemorySSAWalker * getWalker()
InsertionPlace
Used in various insertion functions to specify whether we are talking about the beginning or end of a...
Definition MemorySSA.h:785
LLVM_ABI void insertIntoListsBefore(MemoryAccess *, const BasicBlock *, AccessList::iterator)
LLVM_ABI MemoryUseOrDef * createDefinedAccess(Instruction *, MemoryAccess *, const MemoryUseOrDef *Template=nullptr, bool CreationMustSucceed=true)
DominatorTree & getDomTree() const
Definition MemorySSA.h:722
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Definition MemorySSA.h:714
MemoryAccess * getLiveOnEntryDef() const
Definition MemorySSA.h:738
LLVM_ABI void removeFromLookups(MemoryAccess *)
Properly remove MA from all of MemorySSA's lookup tables.
LLVM_ABI void ensureOptimizedUses()
By default, uses are not optimized during MemorySSA construction.
void verifyDominationNumbers(IterT Blocks) const
Verify that all of the blocks we believe to have valid domination numbers actually have valid dominat...
void verifyPrevDefInPhis(IterT Blocks) const
LLVM_ABI bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in the same basic block, determine whether MemoryAccess A dominates MemoryA...
LLVM_ABI void removeFromLists(MemoryAccess *, bool ShouldDelete=true)
Properly remove MA from all of MemorySSA's lists.
bool isLiveOnEntryDef(const MemoryAccess *MA) const
Return true if MA represents the live on entry value.
Definition MemorySSA.h:734
LLVM_ABI ~MemorySSA()
LLVM_ABI void print(raw_ostream &) const
Class that has the common methods + fields of memory uses/defs.
Definition MemorySSA.h:251
MemoryAccess * getDefiningAccess() const
Get the access that produces the memory state used by this Use.
Definition MemorySSA.h:261
void setDefiningAccess(MemoryAccess *DMA, bool Optimized=false)
Definition MemorySSA.h:294
void setOptimized(MemoryAccess *)
Sets the optimized use for a MemoryDef.
Definition MemorySSA.h:677
Instruction * getMemoryInst() const
Get the instruction that this MemoryUse represents.
Definition MemorySSA.h:258
LLVM_ABI void print(raw_ostream &OS) const
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW, bool ShouldPreserveUseListOrder=false, bool IsForDebug=false) const
Print the module to an output stream with an optional AssemblyAnnotationWriter.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
size_t count(char C) const
Return the number of occurrences of C in the string.
Definition StringRef.h:471
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
op_range operands()
Definition User.h:267
void dropAllReferences()
Drop all references to operands.
Definition User.h:324
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
iterator_range< user_iterator > users()
Definition Value.h:428
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition Value.h:545
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:708
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
bool hasName() const
Definition Value.h:263
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
formatted_raw_ostream - A raw_ostream that wraps another one and keeps track of line and column posit...
An opaque object representing a hash code.
Definition Hashing.h:77
typename base_list_type::iterator iterator
Definition ilist.h:121
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
reverse_iterator rbegin()
CallInst * Call
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:164
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LocationClass< Ty > location(Ty &L)
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
APInt operator*(APInt a, uint64_t RHS)
Definition APInt.h:2261
auto successors(const MachineBasicBlock *BB)
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
auto pred_size(const MachineBasicBlock *BB)
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
Op::Description Desc
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
const AnalysisOptions & getAnalysisOptions(const LLVMContext &C)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
iterator_range< def_chain_iterator< T > > def_chain(T MA, MemoryAccess *UpTo=nullptr)
Definition MemorySSA.h:1363
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
auto find_if_not(R &&Range, UnaryPredicate P)
Definition STLExtras.h:1793
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isAtLeastOrStrongerThan(AtomicOrdering AO, AtomicOrdering Other)
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:76
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
IDFCalculator< false > ForwardIDFCalculator
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
upward_defs_iterator upward_defs_end()
Definition MemorySSA.h:1317
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Instruction::const_succ_iterator const_succ_iterator
Definition CFG.h:127
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:307
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
upward_defs_iterator upward_defs_begin(const UpwardDefsElem &Pair, DominatorTree &DT)
Definition MemorySSA.h:1312
bool isRefSet(const ModRefInfo MRI)
Definition ModRef.h:52
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define MAP(n)
#define N
std::string getEdgeAttributes(const BasicBlock *Node, const_succ_iterator I, DOTFuncMSSAInfo *CFGInfo)
Display the raw branch weights from PGO.
std::string getNodeAttributes(const BasicBlock *Node, DOTFuncMSSAInfo *CFGInfo)
static std::string getEdgeSourceLabel(const BasicBlock *Node, const_succ_iterator I)
std::string getNodeLabel(const BasicBlock *Node, DOTFuncMSSAInfo *CFGInfo)
static std::string getGraphName(DOTFuncMSSAInfo *CFGInfo)
static std::string getEdgeSourceLabel(const void *, EdgeIter)
getEdgeSourceLabel - If you want to label the edge source itself, implement this method.
static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS)
static unsigned getHashValue(const MemoryLocOrCall &MLOC)
An information struct used to provide DenseMap with the various necessary components for a given valu...
pointer_iterator< Function::const_iterator > nodes_iterator
static size_t size(DOTFuncMSSAInfo *CFGInfo)
static NodeRef getEntryNode(DOTFuncMSSAInfo *CFGInfo)
static nodes_iterator nodes_begin(DOTFuncMSSAInfo *CFGInfo)
static nodes_iterator nodes_end(DOTFuncMSSAInfo *CFGInfo)
typename DOTFuncMSSAInfo *::UnknownGraphTypeError NodeRef
Definition GraphTraits.h:94
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)