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