16f1ae631SEugene Zelenko //===-- PredicateInfo.cpp - PredicateInfo Builder--------------------===//
2439042b7SDaniel Berlin //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6439042b7SDaniel Berlin //
76f1ae631SEugene Zelenko //===----------------------------------------------------------------===//
8439042b7SDaniel Berlin //
9439042b7SDaniel Berlin // This file implements the PredicateInfo class.
10439042b7SDaniel Berlin //
116f1ae631SEugene Zelenko //===----------------------------------------------------------------===//
12439042b7SDaniel Berlin 
13439042b7SDaniel Berlin #include "llvm/Transforms/Utils/PredicateInfo.h"
14439042b7SDaniel Berlin #include "llvm/ADT/DenseMap.h"
15439042b7SDaniel Berlin #include "llvm/ADT/DepthFirstIterator.h"
16439042b7SDaniel Berlin #include "llvm/ADT/STLExtras.h"
17439042b7SDaniel Berlin #include "llvm/ADT/SmallPtrSet.h"
18439042b7SDaniel Berlin #include "llvm/Analysis/AssumptionCache.h"
19439042b7SDaniel Berlin #include "llvm/IR/AssemblyAnnotationWriter.h"
20439042b7SDaniel Berlin #include "llvm/IR/Dominators.h"
21439042b7SDaniel Berlin #include "llvm/IR/IRBuilder.h"
22dc5570d1SJeroen Dobbelaere #include "llvm/IR/InstIterator.h"
23439042b7SDaniel Berlin #include "llvm/IR/IntrinsicInst.h"
246f1ae631SEugene Zelenko #include "llvm/IR/Module.h"
25439042b7SDaniel Berlin #include "llvm/IR/PatternMatch.h"
2605da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
2736bc10e7SSimon Pilgrim #include "llvm/Support/CommandLine.h"
28439042b7SDaniel Berlin #include "llvm/Support/Debug.h"
29a4b5c01dSDaniel Berlin #include "llvm/Support/DebugCounter.h"
30439042b7SDaniel Berlin #include "llvm/Support/FormattedStream.h"
31439042b7SDaniel Berlin #include <algorithm>
326f1ae631SEugene Zelenko #define DEBUG_TYPE "predicateinfo"
33439042b7SDaniel Berlin using namespace llvm;
34439042b7SDaniel Berlin using namespace PatternMatch;
35439042b7SDaniel Berlin 
36439042b7SDaniel Berlin INITIALIZE_PASS_BEGIN(PredicateInfoPrinterLegacyPass, "print-predicateinfo",
37439042b7SDaniel Berlin                       "PredicateInfo Printer", false, false)
38439042b7SDaniel Berlin INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
39439042b7SDaniel Berlin INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
40439042b7SDaniel Berlin INITIALIZE_PASS_END(PredicateInfoPrinterLegacyPass, "print-predicateinfo",
41439042b7SDaniel Berlin                     "PredicateInfo Printer", false, false)
42439042b7SDaniel Berlin static cl::opt<bool> VerifyPredicateInfo(
43439042b7SDaniel Berlin     "verify-predicateinfo", cl::init(false), cl::Hidden,
44439042b7SDaniel Berlin     cl::desc("Verify PredicateInfo in legacy printer pass."));
45a4b5c01dSDaniel Berlin DEBUG_COUNTER(RenameCounter, "predicateinfo-rename",
469cd976d0SCraig Topper               "Controls which variables are renamed with predicateinfo");
479cd976d0SCraig Topper 
48ca4ed1e7SNikita Popov // Maximum number of conditions considered for renaming for each branch/assume.
49ca4ed1e7SNikita Popov // This limits renaming of deep and/or chains.
50ca4ed1e7SNikita Popov static const unsigned MaxCondsPerBranch = 8;
51ca4ed1e7SNikita Popov 
526f1ae631SEugene Zelenko namespace {
53fccbda96SDaniel Berlin // Given a predicate info that is a type of branching terminator, get the
54fccbda96SDaniel Berlin // branching block.
getBranchBlock(const PredicateBase * PB)556f1ae631SEugene Zelenko const BasicBlock *getBranchBlock(const PredicateBase *PB) {
56fccbda96SDaniel Berlin   assert(isa<PredicateWithEdge>(PB) &&
57fccbda96SDaniel Berlin          "Only branches and switches should have PHIOnly defs that "
58fccbda96SDaniel Berlin          "require branch blocks.");
59fccbda96SDaniel Berlin   return cast<PredicateWithEdge>(PB)->From;
60fccbda96SDaniel Berlin }
61fccbda96SDaniel Berlin 
62fccbda96SDaniel Berlin // Given a predicate info that is a type of branching terminator, get the
63fccbda96SDaniel Berlin // branching terminator.
getBranchTerminator(const PredicateBase * PB)64fccbda96SDaniel Berlin static Instruction *getBranchTerminator(const PredicateBase *PB) {
65fccbda96SDaniel Berlin   assert(isa<PredicateWithEdge>(PB) &&
66fccbda96SDaniel Berlin          "Not a predicate info type we know how to get a terminator from.");
67fccbda96SDaniel Berlin   return cast<PredicateWithEdge>(PB)->From->getTerminator();
68fccbda96SDaniel Berlin }
69fccbda96SDaniel Berlin 
70fccbda96SDaniel Berlin // Given a predicate info that is a type of branching terminator, get the
71fccbda96SDaniel Berlin // edge this predicate info represents
getBlockEdge(const PredicateBase * PB)72de6c49aeSKazu Hirata std::pair<BasicBlock *, BasicBlock *> getBlockEdge(const PredicateBase *PB) {
73fccbda96SDaniel Berlin   assert(isa<PredicateWithEdge>(PB) &&
74fccbda96SDaniel Berlin          "Not a predicate info type we know how to get an edge from.");
75fccbda96SDaniel Berlin   const auto *PEdge = cast<PredicateWithEdge>(PB);
76fccbda96SDaniel Berlin   return std::make_pair(PEdge->From, PEdge->To);
77fccbda96SDaniel Berlin }
78fccbda96SDaniel Berlin }
79a4b5c01dSDaniel Berlin 
80439042b7SDaniel Berlin namespace llvm {
81439042b7SDaniel Berlin enum LocalNum {
82439042b7SDaniel Berlin   // Operations that must appear first in the block.
83439042b7SDaniel Berlin   LN_First,
84439042b7SDaniel Berlin   // Operations that are somewhere in the middle of the block, and are sorted on
85439042b7SDaniel Berlin   // demand.
86439042b7SDaniel Berlin   LN_Middle,
87439042b7SDaniel Berlin   // Operations that must appear last in a block, like successor phi node uses.
88439042b7SDaniel Berlin   LN_Last
89439042b7SDaniel Berlin };
90439042b7SDaniel Berlin 
91439042b7SDaniel Berlin // Associate global and local DFS info with defs and uses, so we can sort them
92439042b7SDaniel Berlin // into a global domination ordering.
93439042b7SDaniel Berlin struct ValueDFS {
94439042b7SDaniel Berlin   int DFSIn = 0;
95439042b7SDaniel Berlin   int DFSOut = 0;
96439042b7SDaniel Berlin   unsigned int LocalNum = LN_Middle;
97439042b7SDaniel Berlin   // Only one of Def or Use will be set.
98439042b7SDaniel Berlin   Value *Def = nullptr;
99c763fd1aSDaniel Berlin   Use *U = nullptr;
100588e0be3SDaniel Berlin   // Neither PInfo nor EdgeOnly participate in the ordering
101dbe8264cSDaniel Berlin   PredicateBase *PInfo = nullptr;
102588e0be3SDaniel Berlin   bool EdgeOnly = false;
103439042b7SDaniel Berlin };
104439042b7SDaniel Berlin 
1056f1ae631SEugene Zelenko // Perform a strict weak ordering on instructions and arguments.
valueComesBefore(const Value * A,const Value * B)1064331b381SFlorian Hahn static bool valueComesBefore(const Value *A, const Value *B) {
1076f1ae631SEugene Zelenko   auto *ArgA = dyn_cast_or_null<Argument>(A);
1086f1ae631SEugene Zelenko   auto *ArgB = dyn_cast_or_null<Argument>(B);
1096f1ae631SEugene Zelenko   if (ArgA && !ArgB)
1106f1ae631SEugene Zelenko     return true;
1116f1ae631SEugene Zelenko   if (ArgB && !ArgA)
1126f1ae631SEugene Zelenko     return false;
1136f1ae631SEugene Zelenko   if (ArgA && ArgB)
1146f1ae631SEugene Zelenko     return ArgA->getArgNo() < ArgB->getArgNo();
1154331b381SFlorian Hahn   return cast<Instruction>(A)->comesBefore(cast<Instruction>(B));
1166f1ae631SEugene Zelenko }
1176f1ae631SEugene Zelenko 
1184331b381SFlorian Hahn // This compares ValueDFS structures. Doing so allows us to walk the minimum
1194331b381SFlorian Hahn // number of instructions necessary to compute our def/use ordering.
120439042b7SDaniel Berlin struct ValueDFS_Compare {
121c74808b9SFlorian Hahn   DominatorTree &DT;
ValueDFS_Comparellvm::ValueDFS_Compare1224331b381SFlorian Hahn   ValueDFS_Compare(DominatorTree &DT) : DT(DT) {}
123b7df17ecSDaniel Berlin 
operator ()llvm::ValueDFS_Compare124439042b7SDaniel Berlin   bool operator()(const ValueDFS &A, const ValueDFS &B) const {
125439042b7SDaniel Berlin     if (&A == &B)
126439042b7SDaniel Berlin       return false;
127439042b7SDaniel Berlin     // The only case we can't directly compare them is when they in the same
128439042b7SDaniel Berlin     // block, and both have localnum == middle.  In that case, we have to use
129439042b7SDaniel Berlin     // comesbefore to see what the real ordering is, because they are in the
130439042b7SDaniel Berlin     // same basic block.
131439042b7SDaniel Berlin 
132c74808b9SFlorian Hahn     assert((A.DFSIn != B.DFSIn || A.DFSOut == B.DFSOut) &&
133c74808b9SFlorian Hahn            "Equal DFS-in numbers imply equal out numbers");
134c74808b9SFlorian Hahn     bool SameBlock = A.DFSIn == B.DFSIn;
135439042b7SDaniel Berlin 
136dbe8264cSDaniel Berlin     // We want to put the def that will get used for a given set of phi uses,
137dbe8264cSDaniel Berlin     // before those phi uses.
138dbe8264cSDaniel Berlin     // So we sort by edge, then by def.
139dbe8264cSDaniel Berlin     // Note that only phi nodes uses and defs can come last.
140dbe8264cSDaniel Berlin     if (SameBlock && A.LocalNum == LN_Last && B.LocalNum == LN_Last)
141dbe8264cSDaniel Berlin       return comparePHIRelated(A, B);
142dbe8264cSDaniel Berlin 
143c74808b9SFlorian Hahn     bool isADef = A.Def;
144c74808b9SFlorian Hahn     bool isBDef = B.Def;
145439042b7SDaniel Berlin     if (!SameBlock || A.LocalNum != LN_Middle || B.LocalNum != LN_Middle)
146c74808b9SFlorian Hahn       return std::tie(A.DFSIn, A.LocalNum, isADef) <
147c74808b9SFlorian Hahn              std::tie(B.DFSIn, B.LocalNum, isBDef);
148439042b7SDaniel Berlin     return localComesBefore(A, B);
149439042b7SDaniel Berlin   }
150439042b7SDaniel Berlin 
151dbe8264cSDaniel Berlin   // For a phi use, or a non-materialized def, return the edge it represents.
getBlockEdgellvm::ValueDFS_Compare152de6c49aeSKazu Hirata   std::pair<BasicBlock *, BasicBlock *> getBlockEdge(const ValueDFS &VD) const {
153dbe8264cSDaniel Berlin     if (!VD.Def && VD.U) {
154dbe8264cSDaniel Berlin       auto *PHI = cast<PHINode>(VD.U->getUser());
155dbe8264cSDaniel Berlin       return std::make_pair(PHI->getIncomingBlock(*VD.U), PHI->getParent());
156dbe8264cSDaniel Berlin     }
157dbe8264cSDaniel Berlin     // This is really a non-materialized def.
158fccbda96SDaniel Berlin     return ::getBlockEdge(VD.PInfo);
159dbe8264cSDaniel Berlin   }
160dbe8264cSDaniel Berlin 
161dbe8264cSDaniel Berlin   // For two phi related values, return the ordering.
comparePHIRelatedllvm::ValueDFS_Compare162dbe8264cSDaniel Berlin   bool comparePHIRelated(const ValueDFS &A, const ValueDFS &B) const {
163c74808b9SFlorian Hahn     BasicBlock *ASrc, *ADest, *BSrc, *BDest;
164c74808b9SFlorian Hahn     std::tie(ASrc, ADest) = getBlockEdge(A);
165c74808b9SFlorian Hahn     std::tie(BSrc, BDest) = getBlockEdge(B);
166c74808b9SFlorian Hahn 
167c74808b9SFlorian Hahn #ifndef NDEBUG
168c74808b9SFlorian Hahn     // This function should only be used for values in the same BB, check that.
169c74808b9SFlorian Hahn     DomTreeNode *DomASrc = DT.getNode(ASrc);
170c74808b9SFlorian Hahn     DomTreeNode *DomBSrc = DT.getNode(BSrc);
171c74808b9SFlorian Hahn     assert(DomASrc->getDFSNumIn() == (unsigned)A.DFSIn &&
172c74808b9SFlorian Hahn            "DFS numbers for A should match the ones of the source block");
173c74808b9SFlorian Hahn     assert(DomBSrc->getDFSNumIn() == (unsigned)B.DFSIn &&
174c74808b9SFlorian Hahn            "DFS numbers for B should match the ones of the source block");
175c74808b9SFlorian Hahn     assert(A.DFSIn == B.DFSIn && "Values must be in the same block");
176c74808b9SFlorian Hahn #endif
177c74808b9SFlorian Hahn     (void)ASrc;
178c74808b9SFlorian Hahn     (void)BSrc;
179c74808b9SFlorian Hahn 
180c74808b9SFlorian Hahn     // Use DFS numbers to compare destination blocks, to guarantee a
181c74808b9SFlorian Hahn     // deterministic order.
182c74808b9SFlorian Hahn     DomTreeNode *DomADest = DT.getNode(ADest);
183c74808b9SFlorian Hahn     DomTreeNode *DomBDest = DT.getNode(BDest);
184c74808b9SFlorian Hahn     unsigned AIn = DomADest->getDFSNumIn();
185c74808b9SFlorian Hahn     unsigned BIn = DomBDest->getDFSNumIn();
186c74808b9SFlorian Hahn     bool isADef = A.Def;
187c74808b9SFlorian Hahn     bool isBDef = B.Def;
188c74808b9SFlorian Hahn     assert((!A.Def || !A.U) && (!B.Def || !B.U) &&
189c74808b9SFlorian Hahn            "Def and U cannot be set at the same time");
190c74808b9SFlorian Hahn     // Now sort by edge destination and then defs before uses.
191c74808b9SFlorian Hahn     return std::tie(AIn, isADef) < std::tie(BIn, isBDef);
192dbe8264cSDaniel Berlin   }
193dbe8264cSDaniel Berlin 
194439042b7SDaniel Berlin   // Get the definition of an instruction that occurs in the middle of a block.
getMiddleDefllvm::ValueDFS_Compare195439042b7SDaniel Berlin   Value *getMiddleDef(const ValueDFS &VD) const {
196439042b7SDaniel Berlin     if (VD.Def)
197439042b7SDaniel Berlin       return VD.Def;
198439042b7SDaniel Berlin     // It's possible for the defs and uses to be null.  For branches, the local
199439042b7SDaniel Berlin     // numbering will say the placed predicaeinfos should go first (IE
200439042b7SDaniel Berlin     // LN_beginning), so we won't be in this function. For assumes, we will end
201439042b7SDaniel Berlin     // up here, beause we need to order the def we will place relative to the
202353fa440SNikita Popov     // assume.  So for the purpose of ordering, we pretend the def is right
203353fa440SNikita Popov     // after the assume, because that is where we will insert the info.
204c763fd1aSDaniel Berlin     if (!VD.U) {
205439042b7SDaniel Berlin       assert(VD.PInfo &&
206439042b7SDaniel Berlin              "No def, no use, and no predicateinfo should not occur");
207439042b7SDaniel Berlin       assert(isa<PredicateAssume>(VD.PInfo) &&
208439042b7SDaniel Berlin              "Middle of block should only occur for assumes");
209353fa440SNikita Popov       return cast<PredicateAssume>(VD.PInfo)->AssumeInst->getNextNode();
210439042b7SDaniel Berlin     }
211439042b7SDaniel Berlin     return nullptr;
212439042b7SDaniel Berlin   }
213439042b7SDaniel Berlin 
214439042b7SDaniel Berlin   // Return either the Def, if it's not null, or the user of the Use, if the def
215439042b7SDaniel Berlin   // is null.
getDefOrUserllvm::ValueDFS_Compare216c763fd1aSDaniel Berlin   const Instruction *getDefOrUser(const Value *Def, const Use *U) const {
217439042b7SDaniel Berlin     if (Def)
218439042b7SDaniel Berlin       return cast<Instruction>(Def);
219c763fd1aSDaniel Berlin     return cast<Instruction>(U->getUser());
220439042b7SDaniel Berlin   }
221439042b7SDaniel Berlin 
222439042b7SDaniel Berlin   // This performs the necessary local basic block ordering checks to tell
223439042b7SDaniel Berlin   // whether A comes before B, where both are in the same basic block.
localComesBeforellvm::ValueDFS_Compare224439042b7SDaniel Berlin   bool localComesBefore(const ValueDFS &A, const ValueDFS &B) const {
225439042b7SDaniel Berlin     auto *ADef = getMiddleDef(A);
226439042b7SDaniel Berlin     auto *BDef = getMiddleDef(B);
227439042b7SDaniel Berlin 
228439042b7SDaniel Berlin     // See if we have real values or uses. If we have real values, we are
229439042b7SDaniel Berlin     // guaranteed they are instructions or arguments. No matter what, we are
230439042b7SDaniel Berlin     // guaranteed they are in the same block if they are instructions.
231439042b7SDaniel Berlin     auto *ArgA = dyn_cast_or_null<Argument>(ADef);
232439042b7SDaniel Berlin     auto *ArgB = dyn_cast_or_null<Argument>(BDef);
233439042b7SDaniel Berlin 
234b7df17ecSDaniel Berlin     if (ArgA || ArgB)
2354331b381SFlorian Hahn       return valueComesBefore(ArgA, ArgB);
236439042b7SDaniel Berlin 
237c763fd1aSDaniel Berlin     auto *AInst = getDefOrUser(ADef, A.U);
238c763fd1aSDaniel Berlin     auto *BInst = getDefOrUser(BDef, B.U);
2394331b381SFlorian Hahn     return valueComesBefore(AInst, BInst);
240439042b7SDaniel Berlin   }
241439042b7SDaniel Berlin };
242439042b7SDaniel Berlin 
243a42fd18dSNikita Popov class PredicateInfoBuilder {
244a42fd18dSNikita Popov   // Used to store information about each value we might rename.
245a42fd18dSNikita Popov   struct ValueInfo {
246a42fd18dSNikita Popov     SmallVector<PredicateBase *, 4> Infos;
247a42fd18dSNikita Popov   };
248439042b7SDaniel Berlin 
249a42fd18dSNikita Popov   PredicateInfo &PI;
250a42fd18dSNikita Popov   Function &F;
251a42fd18dSNikita Popov   DominatorTree &DT;
252a42fd18dSNikita Popov   AssumptionCache &AC;
253a42fd18dSNikita Popov 
254a42fd18dSNikita Popov   // This stores info about each operand or comparison result we make copies
255a42fd18dSNikita Popov   // of. The real ValueInfos start at index 1, index 0 is unused so that we
256a42fd18dSNikita Popov   // can more easily detect invalid indexing.
257a42fd18dSNikita Popov   SmallVector<ValueInfo, 32> ValueInfos;
258a42fd18dSNikita Popov 
259a42fd18dSNikita Popov   // This gives the index into the ValueInfos array for a given Value. Because
260a42fd18dSNikita Popov   // 0 is not a valid Value Info index, you can use DenseMap::lookup and tell
261a42fd18dSNikita Popov   // whether it returned a valid result.
262a42fd18dSNikita Popov   DenseMap<Value *, unsigned int> ValueInfoNums;
263a42fd18dSNikita Popov 
264a42fd18dSNikita Popov   // The set of edges along which we can only handle phi uses, due to critical
265a42fd18dSNikita Popov   // edges.
266a42fd18dSNikita Popov   DenseSet<std::pair<BasicBlock *, BasicBlock *>> EdgeUsesOnly;
267a42fd18dSNikita Popov 
268a42fd18dSNikita Popov   ValueInfo &getOrCreateValueInfo(Value *);
269a42fd18dSNikita Popov   const ValueInfo &getValueInfo(Value *) const;
270a42fd18dSNikita Popov 
271a42fd18dSNikita Popov   void processAssume(IntrinsicInst *, BasicBlock *,
272a42fd18dSNikita Popov                      SmallVectorImpl<Value *> &OpsToRename);
273a42fd18dSNikita Popov   void processBranch(BranchInst *, BasicBlock *,
274a42fd18dSNikita Popov                      SmallVectorImpl<Value *> &OpsToRename);
275a42fd18dSNikita Popov   void processSwitch(SwitchInst *, BasicBlock *,
276a42fd18dSNikita Popov                      SmallVectorImpl<Value *> &OpsToRename);
277a42fd18dSNikita Popov   void renameUses(SmallVectorImpl<Value *> &OpsToRename);
278a42fd18dSNikita Popov   void addInfoFor(SmallVectorImpl<Value *> &OpsToRename, Value *Op,
279a42fd18dSNikita Popov                   PredicateBase *PB);
280a42fd18dSNikita Popov 
281a42fd18dSNikita Popov   typedef SmallVectorImpl<ValueDFS> ValueDFSStack;
282a42fd18dSNikita Popov   void convertUsesToDFSOrdered(Value *, SmallVectorImpl<ValueDFS> &);
283a42fd18dSNikita Popov   Value *materializeStack(unsigned int &, ValueDFSStack &, Value *);
284a42fd18dSNikita Popov   bool stackIsInScope(const ValueDFSStack &, const ValueDFS &) const;
285a42fd18dSNikita Popov   void popStackUntilDFSScope(ValueDFSStack &, const ValueDFS &);
286a42fd18dSNikita Popov 
287a42fd18dSNikita Popov public:
PredicateInfoBuilder(PredicateInfo & PI,Function & F,DominatorTree & DT,AssumptionCache & AC)288a42fd18dSNikita Popov   PredicateInfoBuilder(PredicateInfo &PI, Function &F, DominatorTree &DT,
289a42fd18dSNikita Popov                        AssumptionCache &AC)
2904331b381SFlorian Hahn       : PI(PI), F(F), DT(DT), AC(AC) {
291a42fd18dSNikita Popov     // Push an empty operand info so that we can detect 0 as not finding one
292a42fd18dSNikita Popov     ValueInfos.resize(1);
293a42fd18dSNikita Popov   }
294a42fd18dSNikita Popov 
295a42fd18dSNikita Popov   void buildPredicateInfo();
296a42fd18dSNikita Popov };
297a42fd18dSNikita Popov 
stackIsInScope(const ValueDFSStack & Stack,const ValueDFS & VDUse) const298a42fd18dSNikita Popov bool PredicateInfoBuilder::stackIsInScope(const ValueDFSStack &Stack,
299dbe8264cSDaniel Berlin                                           const ValueDFS &VDUse) const {
300439042b7SDaniel Berlin   if (Stack.empty())
301439042b7SDaniel Berlin     return false;
302dbe8264cSDaniel Berlin   // If it's a phi only use, make sure it's for this phi node edge, and that the
303dbe8264cSDaniel Berlin   // use is in a phi node.  If it's anything else, and the top of the stack is
304588e0be3SDaniel Berlin   // EdgeOnly, we need to pop the stack.  We deliberately sort phi uses next to
305dbe8264cSDaniel Berlin   // the defs they must go with so that we can know it's time to pop the stack
306dbe8264cSDaniel Berlin   // when we hit the end of the phi uses for a given def.
307588e0be3SDaniel Berlin   if (Stack.back().EdgeOnly) {
308dbe8264cSDaniel Berlin     if (!VDUse.U)
309dbe8264cSDaniel Berlin       return false;
310dbe8264cSDaniel Berlin     auto *PHI = dyn_cast<PHINode>(VDUse.U->getUser());
311dbe8264cSDaniel Berlin     if (!PHI)
312dbe8264cSDaniel Berlin       return false;
313fccbda96SDaniel Berlin     // Check edge
314dbe8264cSDaniel Berlin     BasicBlock *EdgePred = PHI->getIncomingBlock(*VDUse.U);
315fccbda96SDaniel Berlin     if (EdgePred != getBranchBlock(Stack.back().PInfo))
316dbe8264cSDaniel Berlin       return false;
317588e0be3SDaniel Berlin 
318588e0be3SDaniel Berlin     // Use dominates, which knows how to handle edge dominance.
319fccbda96SDaniel Berlin     return DT.dominates(getBlockEdge(Stack.back().PInfo), *VDUse.U);
320439042b7SDaniel Berlin   }
321439042b7SDaniel Berlin 
322dbe8264cSDaniel Berlin   return (VDUse.DFSIn >= Stack.back().DFSIn &&
323dbe8264cSDaniel Berlin           VDUse.DFSOut <= Stack.back().DFSOut);
324dbe8264cSDaniel Berlin }
325dbe8264cSDaniel Berlin 
popStackUntilDFSScope(ValueDFSStack & Stack,const ValueDFS & VD)326a42fd18dSNikita Popov void PredicateInfoBuilder::popStackUntilDFSScope(ValueDFSStack &Stack,
327dbe8264cSDaniel Berlin                                                  const ValueDFS &VD) {
328dbe8264cSDaniel Berlin   while (!Stack.empty() && !stackIsInScope(Stack, VD))
329439042b7SDaniel Berlin     Stack.pop_back();
330439042b7SDaniel Berlin }
331439042b7SDaniel Berlin 
332439042b7SDaniel Berlin // Convert the uses of Op into a vector of uses, associating global and local
333439042b7SDaniel Berlin // DFS info with each one.
convertUsesToDFSOrdered(Value * Op,SmallVectorImpl<ValueDFS> & DFSOrderedSet)334a42fd18dSNikita Popov void PredicateInfoBuilder::convertUsesToDFSOrdered(
335439042b7SDaniel Berlin     Value *Op, SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
336439042b7SDaniel Berlin   for (auto &U : Op->uses()) {
337439042b7SDaniel Berlin     if (auto *I = dyn_cast<Instruction>(U.getUser())) {
338439042b7SDaniel Berlin       ValueDFS VD;
339439042b7SDaniel Berlin       // Put the phi node uses in the incoming block.
340439042b7SDaniel Berlin       BasicBlock *IBlock;
341439042b7SDaniel Berlin       if (auto *PN = dyn_cast<PHINode>(I)) {
342439042b7SDaniel Berlin         IBlock = PN->getIncomingBlock(U);
343439042b7SDaniel Berlin         // Make phi node users appear last in the incoming block
344439042b7SDaniel Berlin         // they are from.
345439042b7SDaniel Berlin         VD.LocalNum = LN_Last;
346439042b7SDaniel Berlin       } else {
347439042b7SDaniel Berlin         // If it's not a phi node use, it is somewhere in the middle of the
348439042b7SDaniel Berlin         // block.
349439042b7SDaniel Berlin         IBlock = I->getParent();
350439042b7SDaniel Berlin         VD.LocalNum = LN_Middle;
351439042b7SDaniel Berlin       }
352439042b7SDaniel Berlin       DomTreeNode *DomNode = DT.getNode(IBlock);
353439042b7SDaniel Berlin       // It's possible our use is in an unreachable block. Skip it if so.
354439042b7SDaniel Berlin       if (!DomNode)
355439042b7SDaniel Berlin         continue;
356439042b7SDaniel Berlin       VD.DFSIn = DomNode->getDFSNumIn();
357439042b7SDaniel Berlin       VD.DFSOut = DomNode->getDFSNumOut();
358c763fd1aSDaniel Berlin       VD.U = &U;
359439042b7SDaniel Berlin       DFSOrderedSet.push_back(VD);
360439042b7SDaniel Berlin     }
361439042b7SDaniel Berlin   }
362439042b7SDaniel Berlin }
363439042b7SDaniel Berlin 
shouldRename(Value * V)364ca4ed1e7SNikita Popov bool shouldRename(Value *V) {
365ca4ed1e7SNikita Popov   // Only want real values, not constants.  Additionally, operands with one use
366ca4ed1e7SNikita Popov   // are only being used in the comparison, which means they will not be useful
367ca4ed1e7SNikita Popov   // for us to consider for predicateinfo.
368ca4ed1e7SNikita Popov   return (isa<Instruction>(V) || isa<Argument>(V)) && !V->hasOneUse();
369ca4ed1e7SNikita Popov }
370ca4ed1e7SNikita Popov 
371439042b7SDaniel Berlin // Collect relevant operations from Comparison that we may want to insert copies
372439042b7SDaniel Berlin // for.
collectCmpOps(CmpInst * Comparison,SmallVectorImpl<Value * > & CmpOperands)3736f1ae631SEugene Zelenko void collectCmpOps(CmpInst *Comparison, SmallVectorImpl<Value *> &CmpOperands) {
374439042b7SDaniel Berlin   auto *Op0 = Comparison->getOperand(0);
375439042b7SDaniel Berlin   auto *Op1 = Comparison->getOperand(1);
376439042b7SDaniel Berlin   if (Op0 == Op1)
377439042b7SDaniel Berlin     return;
378ca4ed1e7SNikita Popov 
379439042b7SDaniel Berlin   CmpOperands.push_back(Op0);
380439042b7SDaniel Berlin   CmpOperands.push_back(Op1);
381439042b7SDaniel Berlin }
382439042b7SDaniel Berlin 
383588e0be3SDaniel Berlin // Add Op, PB to the list of value infos for Op, and mark Op to be renamed.
addInfoFor(SmallVectorImpl<Value * > & OpsToRename,Value * Op,PredicateBase * PB)384a42fd18dSNikita Popov void PredicateInfoBuilder::addInfoFor(SmallVectorImpl<Value *> &OpsToRename,
385a42fd18dSNikita Popov                                       Value *Op, PredicateBase *PB) {
386588e0be3SDaniel Berlin   auto &OperandInfo = getOrCreateValueInfo(Op);
387c0d0e3bdSFlorian Hahn   if (OperandInfo.Infos.empty())
388c0d0e3bdSFlorian Hahn     OpsToRename.push_back(Op);
389a42fd18dSNikita Popov   PI.AllInfos.push_back(PB);
390588e0be3SDaniel Berlin   OperandInfo.Infos.push_back(PB);
391588e0be3SDaniel Berlin }
392588e0be3SDaniel Berlin 
393439042b7SDaniel Berlin // Process an assume instruction and place relevant operations we want to rename
394439042b7SDaniel Berlin // into OpsToRename.
processAssume(IntrinsicInst * II,BasicBlock * AssumeBB,SmallVectorImpl<Value * > & OpsToRename)395a42fd18dSNikita Popov void PredicateInfoBuilder::processAssume(
396a42fd18dSNikita Popov     IntrinsicInst *II, BasicBlock *AssumeBB,
397c0d0e3bdSFlorian Hahn     SmallVectorImpl<Value *> &OpsToRename) {
398ca4ed1e7SNikita Popov   SmallVector<Value *, 4> Worklist;
399ca4ed1e7SNikita Popov   SmallPtrSet<Value *, 4> Visited;
400ca4ed1e7SNikita Popov   Worklist.push_back(II->getOperand(0));
401ca4ed1e7SNikita Popov   while (!Worklist.empty()) {
402ca4ed1e7SNikita Popov     Value *Cond = Worklist.pop_back_val();
403ca4ed1e7SNikita Popov     if (!Visited.insert(Cond).second)
404ca4ed1e7SNikita Popov       continue;
405ca4ed1e7SNikita Popov     if (Visited.size() > MaxCondsPerBranch)
406ca4ed1e7SNikita Popov       break;
407588e0be3SDaniel Berlin 
408ca4ed1e7SNikita Popov     Value *Op0, *Op1;
4091c6d1e57SNikita Popov     if (match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
410ca4ed1e7SNikita Popov       Worklist.push_back(Op1);
411ca4ed1e7SNikita Popov       Worklist.push_back(Op0);
412439042b7SDaniel Berlin     }
413ca4ed1e7SNikita Popov 
414ca4ed1e7SNikita Popov     SmallVector<Value *, 4> Values;
415ca4ed1e7SNikita Popov     Values.push_back(Cond);
416ca4ed1e7SNikita Popov     if (auto *Cmp = dyn_cast<CmpInst>(Cond))
417ca4ed1e7SNikita Popov       collectCmpOps(Cmp, Values);
418ca4ed1e7SNikita Popov 
419ca4ed1e7SNikita Popov     for (Value *V : Values) {
420ca4ed1e7SNikita Popov       if (shouldRename(V)) {
421ca4ed1e7SNikita Popov         auto *PA = new PredicateAssume(V, II, Cond);
422ca4ed1e7SNikita Popov         addInfoFor(OpsToRename, V, PA);
423439042b7SDaniel Berlin       }
424439042b7SDaniel Berlin     }
425439042b7SDaniel Berlin   }
426439042b7SDaniel Berlin }
427439042b7SDaniel Berlin 
428439042b7SDaniel Berlin // Process a block terminating branch, and place relevant operations to be
429439042b7SDaniel Berlin // renamed into OpsToRename.
processBranch(BranchInst * BI,BasicBlock * BranchBB,SmallVectorImpl<Value * > & OpsToRename)430a42fd18dSNikita Popov void PredicateInfoBuilder::processBranch(
431a42fd18dSNikita Popov     BranchInst *BI, BasicBlock *BranchBB,
432c0d0e3bdSFlorian Hahn     SmallVectorImpl<Value *> &OpsToRename) {
433439042b7SDaniel Berlin   BasicBlock *FirstBB = BI->getSuccessor(0);
434439042b7SDaniel Berlin   BasicBlock *SecondBB = BI->getSuccessor(1);
435588e0be3SDaniel Berlin 
436ca4ed1e7SNikita Popov   for (BasicBlock *Succ : {FirstBB, SecondBB}) {
437ca4ed1e7SNikita Popov     bool TakenEdge = Succ == FirstBB;
438588e0be3SDaniel Berlin     // Don't try to insert on a self-edge. This is mainly because we will
439588e0be3SDaniel Berlin     // eliminate during renaming anyway.
440588e0be3SDaniel Berlin     if (Succ == BranchBB)
441588e0be3SDaniel Berlin       continue;
442ca4ed1e7SNikita Popov 
443ca4ed1e7SNikita Popov     SmallVector<Value *, 4> Worklist;
444ca4ed1e7SNikita Popov     SmallPtrSet<Value *, 4> Visited;
445ca4ed1e7SNikita Popov     Worklist.push_back(BI->getCondition());
446ca4ed1e7SNikita Popov     while (!Worklist.empty()) {
447ca4ed1e7SNikita Popov       Value *Cond = Worklist.pop_back_val();
448ca4ed1e7SNikita Popov       if (!Visited.insert(Cond).second)
449588e0be3SDaniel Berlin         continue;
450ca4ed1e7SNikita Popov       if (Visited.size() > MaxCondsPerBranch)
451ca4ed1e7SNikita Popov         break;
452ca4ed1e7SNikita Popov 
453ca4ed1e7SNikita Popov       Value *Op0, *Op1;
4541c6d1e57SNikita Popov       if (TakenEdge ? match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))
4551c6d1e57SNikita Popov                     : match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
456ca4ed1e7SNikita Popov         Worklist.push_back(Op1);
457ca4ed1e7SNikita Popov         Worklist.push_back(Op0);
458ca4ed1e7SNikita Popov       }
459ca4ed1e7SNikita Popov 
460ca4ed1e7SNikita Popov       SmallVector<Value *, 4> Values;
461ca4ed1e7SNikita Popov       Values.push_back(Cond);
462ca4ed1e7SNikita Popov       if (auto *Cmp = dyn_cast<CmpInst>(Cond))
463ca4ed1e7SNikita Popov         collectCmpOps(Cmp, Values);
464ca4ed1e7SNikita Popov 
465ca4ed1e7SNikita Popov       for (Value *V : Values) {
466ca4ed1e7SNikita Popov         if (shouldRename(V)) {
467588e0be3SDaniel Berlin           PredicateBase *PB =
468ca4ed1e7SNikita Popov               new PredicateBranch(V, BranchBB, Succ, Cond, TakenEdge);
469ca4ed1e7SNikita Popov           addInfoFor(OpsToRename, V, PB);
470588e0be3SDaniel Berlin           if (!Succ->getSinglePredecessor())
471588e0be3SDaniel Berlin             EdgeUsesOnly.insert({BranchBB, Succ});
472588e0be3SDaniel Berlin         }
473439042b7SDaniel Berlin       }
474439042b7SDaniel Berlin     }
475439042b7SDaniel Berlin   }
476439042b7SDaniel Berlin }
477fccbda96SDaniel Berlin // Process a block terminating switch, and place relevant operations to be
478fccbda96SDaniel Berlin // renamed into OpsToRename.
processSwitch(SwitchInst * SI,BasicBlock * BranchBB,SmallVectorImpl<Value * > & OpsToRename)479a42fd18dSNikita Popov void PredicateInfoBuilder::processSwitch(
480a42fd18dSNikita Popov     SwitchInst *SI, BasicBlock *BranchBB,
481c0d0e3bdSFlorian Hahn     SmallVectorImpl<Value *> &OpsToRename) {
482fccbda96SDaniel Berlin   Value *Op = SI->getCondition();
483fccbda96SDaniel Berlin   if ((!isa<Instruction>(Op) && !isa<Argument>(Op)) || Op->hasOneUse())
484fccbda96SDaniel Berlin     return;
485fccbda96SDaniel Berlin 
486fccbda96SDaniel Berlin   // Remember how many outgoing edges there are to every successor.
487fccbda96SDaniel Berlin   SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
488fccbda96SDaniel Berlin   for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
489fccbda96SDaniel Berlin     BasicBlock *TargetBlock = SI->getSuccessor(i);
490fccbda96SDaniel Berlin     ++SwitchEdges[TargetBlock];
491fccbda96SDaniel Berlin   }
492fccbda96SDaniel Berlin 
493fccbda96SDaniel Berlin   // Now propagate info for each case value
494fccbda96SDaniel Berlin   for (auto C : SI->cases()) {
495fccbda96SDaniel Berlin     BasicBlock *TargetBlock = C.getCaseSuccessor();
496fccbda96SDaniel Berlin     if (SwitchEdges.lookup(TargetBlock) == 1) {
497fccbda96SDaniel Berlin       PredicateSwitch *PS = new PredicateSwitch(
498fccbda96SDaniel Berlin           Op, SI->getParent(), TargetBlock, C.getCaseValue(), SI);
499fccbda96SDaniel Berlin       addInfoFor(OpsToRename, Op, PS);
500fccbda96SDaniel Berlin       if (!TargetBlock->getSinglePredecessor())
501fccbda96SDaniel Berlin         EdgeUsesOnly.insert({BranchBB, TargetBlock});
502fccbda96SDaniel Berlin     }
503fccbda96SDaniel Berlin   }
504fccbda96SDaniel Berlin }
505439042b7SDaniel Berlin 
506439042b7SDaniel Berlin // Build predicate info for our function
buildPredicateInfo()507a42fd18dSNikita Popov void PredicateInfoBuilder::buildPredicateInfo() {
508439042b7SDaniel Berlin   DT.updateDFSNumbers();
509439042b7SDaniel Berlin   // Collect operands to rename from all conditional branch terminators, as well
510439042b7SDaniel Berlin   // as assume statements.
511c0d0e3bdSFlorian Hahn   SmallVector<Value *, 8> OpsToRename;
512439042b7SDaniel Berlin   for (auto DTN : depth_first(DT.getRootNode())) {
513439042b7SDaniel Berlin     BasicBlock *BranchBB = DTN->getBlock();
514439042b7SDaniel Berlin     if (auto *BI = dyn_cast<BranchInst>(BranchBB->getTerminator())) {
515439042b7SDaniel Berlin       if (!BI->isConditional())
516439042b7SDaniel Berlin         continue;
5176d2db9edSDaniel Berlin       // Can't insert conditional information if they all go to the same place.
5186d2db9edSDaniel Berlin       if (BI->getSuccessor(0) == BI->getSuccessor(1))
5196d2db9edSDaniel Berlin         continue;
520439042b7SDaniel Berlin       processBranch(BI, BranchBB, OpsToRename);
521fccbda96SDaniel Berlin     } else if (auto *SI = dyn_cast<SwitchInst>(BranchBB->getTerminator())) {
522fccbda96SDaniel Berlin       processSwitch(SI, BranchBB, OpsToRename);
523439042b7SDaniel Berlin     }
524439042b7SDaniel Berlin   }
525606aa622SMichael Kruse   for (auto &Assume : AC.assumptions()) {
526606aa622SMichael Kruse     if (auto *II = dyn_cast_or_null<IntrinsicInst>(Assume))
527606aa622SMichael Kruse       if (DT.isReachableFromEntry(II->getParent()))
528606aa622SMichael Kruse         processAssume(II, II->getParent(), OpsToRename);
529439042b7SDaniel Berlin   }
530439042b7SDaniel Berlin   // Now rename all our operations.
531439042b7SDaniel Berlin   renameUses(OpsToRename);
532439042b7SDaniel Berlin }
533fccbda96SDaniel Berlin 
534fccbda96SDaniel Berlin // Given the renaming stack, make all the operands currently on the stack real
535fccbda96SDaniel Berlin // by inserting them into the IR.  Return the last operation's value.
materializeStack(unsigned int & Counter,ValueDFSStack & RenameStack,Value * OrigOp)536a42fd18dSNikita Popov Value *PredicateInfoBuilder::materializeStack(unsigned int &Counter,
537439042b7SDaniel Berlin                                              ValueDFSStack &RenameStack,
538439042b7SDaniel Berlin                                              Value *OrigOp) {
539439042b7SDaniel Berlin   // Find the first thing we have to materialize
540439042b7SDaniel Berlin   auto RevIter = RenameStack.rbegin();
541439042b7SDaniel Berlin   for (; RevIter != RenameStack.rend(); ++RevIter)
542439042b7SDaniel Berlin     if (RevIter->Def)
543439042b7SDaniel Berlin       break;
544439042b7SDaniel Berlin 
545439042b7SDaniel Berlin   size_t Start = RevIter - RenameStack.rbegin();
546439042b7SDaniel Berlin   // The maximum number of things we should be trying to materialize at once
547439042b7SDaniel Berlin   // right now is 4, depending on if we had an assume, a branch, and both used
548439042b7SDaniel Berlin   // and of conditions.
549439042b7SDaniel Berlin   for (auto RenameIter = RenameStack.end() - Start;
550439042b7SDaniel Berlin        RenameIter != RenameStack.end(); ++RenameIter) {
551439042b7SDaniel Berlin     auto *Op =
552439042b7SDaniel Berlin         RenameIter == RenameStack.begin() ? OrigOp : (RenameIter - 1)->Def;
553439042b7SDaniel Berlin     ValueDFS &Result = *RenameIter;
554439042b7SDaniel Berlin     auto *ValInfo = Result.PInfo;
555b805e944SFlorian Hahn     ValInfo->RenamedOp = (RenameStack.end() - Start) == RenameStack.begin()
556b805e944SFlorian Hahn                              ? OrigOp
557b805e944SFlorian Hahn                              : (RenameStack.end() - Start - 1)->Def;
558fccbda96SDaniel Berlin     // For edge predicates, we can just place the operand in the block before
559dbe8264cSDaniel Berlin     // the terminator.  For assume, we have to place it right before the assume
560dbe8264cSDaniel Berlin     // to ensure we dominate all of our uses.  Always insert right before the
561dbe8264cSDaniel Berlin     // relevant instruction (terminator, assume), so that we insert in proper
562dbe8264cSDaniel Berlin     // order in the case of multiple predicateinfo in the same block.
563*03b8c69dSJeroen Dobbelaere     // The number of named values is used to detect if a new declaration was
564*03b8c69dSJeroen Dobbelaere     // added. If so, that declaration is tracked so that it can be removed when
565*03b8c69dSJeroen Dobbelaere     // the analysis is done. The corner case were a new declaration results in
566*03b8c69dSJeroen Dobbelaere     // a name clash and the old name being renamed is not considered as that
567*03b8c69dSJeroen Dobbelaere     // represents an invalid module.
568fccbda96SDaniel Berlin     if (isa<PredicateWithEdge>(ValInfo)) {
569fccbda96SDaniel Berlin       IRBuilder<> B(getBranchTerminator(ValInfo));
570*03b8c69dSJeroen Dobbelaere       auto NumDecls = F.getParent()->getNumNamedValues();
571*03b8c69dSJeroen Dobbelaere       Function *IF = Intrinsic::getDeclaration(
572*03b8c69dSJeroen Dobbelaere           F.getParent(), Intrinsic::ssa_copy, Op->getType());
573*03b8c69dSJeroen Dobbelaere       if (NumDecls != F.getParent()->getNumNamedValues())
574dc5570d1SJeroen Dobbelaere         PI.CreatedDeclarations.insert(IF);
575588e0be3SDaniel Berlin       CallInst *PIC =
576588e0be3SDaniel Berlin           B.CreateCall(IF, Op, Op->getName() + "." + Twine(Counter++));
577a42fd18dSNikita Popov       PI.PredicateMap.insert({PIC, ValInfo});
578439042b7SDaniel Berlin       Result.Def = PIC;
579439042b7SDaniel Berlin     } else {
580439042b7SDaniel Berlin       auto *PAssume = dyn_cast<PredicateAssume>(ValInfo);
581439042b7SDaniel Berlin       assert(PAssume &&
582439042b7SDaniel Berlin              "Should not have gotten here without it being an assume");
583353fa440SNikita Popov       // Insert the predicate directly after the assume. While it also holds
584353fa440SNikita Popov       // directly before it, assume(i1 true) is not a useful fact.
585353fa440SNikita Popov       IRBuilder<> B(PAssume->AssumeInst->getNextNode());
586*03b8c69dSJeroen Dobbelaere       auto NumDecls = F.getParent()->getNumNamedValues();
587*03b8c69dSJeroen Dobbelaere       Function *IF = Intrinsic::getDeclaration(
588*03b8c69dSJeroen Dobbelaere           F.getParent(), Intrinsic::ssa_copy, Op->getType());
589*03b8c69dSJeroen Dobbelaere       if (NumDecls != F.getParent()->getNumNamedValues())
590dc5570d1SJeroen Dobbelaere         PI.CreatedDeclarations.insert(IF);
591588e0be3SDaniel Berlin       CallInst *PIC = B.CreateCall(IF, Op);
592a42fd18dSNikita Popov       PI.PredicateMap.insert({PIC, ValInfo});
593439042b7SDaniel Berlin       Result.Def = PIC;
594439042b7SDaniel Berlin     }
595439042b7SDaniel Berlin   }
596439042b7SDaniel Berlin   return RenameStack.back().Def;
597439042b7SDaniel Berlin }
598439042b7SDaniel Berlin 
599439042b7SDaniel Berlin // Instead of the standard SSA renaming algorithm, which is O(Number of
600439042b7SDaniel Berlin // instructions), and walks the entire dominator tree, we walk only the defs +
601439042b7SDaniel Berlin // uses.  The standard SSA renaming algorithm does not really rely on the
602439042b7SDaniel Berlin // dominator tree except to order the stack push/pops of the renaming stacks, so
603439042b7SDaniel Berlin // that defs end up getting pushed before hitting the correct uses.  This does
604439042b7SDaniel Berlin // not require the dominator tree, only the *order* of the dominator tree. The
605439042b7SDaniel Berlin // complete and correct ordering of the defs and uses, in dominator tree is
606439042b7SDaniel Berlin // contained in the DFS numbering of the dominator tree. So we sort the defs and
607439042b7SDaniel Berlin // uses into the DFS ordering, and then just use the renaming stack as per
608439042b7SDaniel Berlin // normal, pushing when we hit a def (which is a predicateinfo instruction),
609439042b7SDaniel Berlin // popping when we are out of the dfs scope for that def, and replacing any uses
610439042b7SDaniel Berlin // with top of stack if it exists.  In order to handle liveness without
611439042b7SDaniel Berlin // propagating liveness info, we don't actually insert the predicateinfo
612439042b7SDaniel Berlin // instruction def until we see a use that it would dominate.  Once we see such
613439042b7SDaniel Berlin // a use, we materialize the predicateinfo instruction in the right place and
614439042b7SDaniel Berlin // use it.
615439042b7SDaniel Berlin //
616439042b7SDaniel Berlin // TODO: Use this algorithm to perform fast single-variable renaming in
617439042b7SDaniel Berlin // promotememtoreg and memoryssa.
renameUses(SmallVectorImpl<Value * > & OpsToRename)618a42fd18dSNikita Popov void PredicateInfoBuilder::renameUses(SmallVectorImpl<Value *> &OpsToRename) {
6194331b381SFlorian Hahn   ValueDFS_Compare Compare(DT);
620439042b7SDaniel Berlin   // Compute liveness, and rename in O(uses) per Op.
621439042b7SDaniel Berlin   for (auto *Op : OpsToRename) {
6225ac26298SFlorian Hahn     LLVM_DEBUG(dbgs() << "Visiting " << *Op << "\n");
623439042b7SDaniel Berlin     unsigned Counter = 0;
624439042b7SDaniel Berlin     SmallVector<ValueDFS, 16> OrderedUses;
625439042b7SDaniel Berlin     const auto &ValueInfo = getValueInfo(Op);
626439042b7SDaniel Berlin     // Insert the possible copies into the def/use list.
627439042b7SDaniel Berlin     // They will become real copies if we find a real use for them, and never
628439042b7SDaniel Berlin     // created otherwise.
629439042b7SDaniel Berlin     for (auto &PossibleCopy : ValueInfo.Infos) {
630439042b7SDaniel Berlin       ValueDFS VD;
631439042b7SDaniel Berlin       // Determine where we are going to place the copy by the copy type.
632439042b7SDaniel Berlin       // The predicate info for branches always come first, they will get
633439042b7SDaniel Berlin       // materialized in the split block at the top of the block.
634439042b7SDaniel Berlin       // The predicate info for assumes will be somewhere in the middle,
635439042b7SDaniel Berlin       // it will get materialized in front of the assume.
636dbe8264cSDaniel Berlin       if (const auto *PAssume = dyn_cast<PredicateAssume>(PossibleCopy)) {
637439042b7SDaniel Berlin         VD.LocalNum = LN_Middle;
638dbe8264cSDaniel Berlin         DomTreeNode *DomNode = DT.getNode(PAssume->AssumeInst->getParent());
639439042b7SDaniel Berlin         if (!DomNode)
640439042b7SDaniel Berlin           continue;
641439042b7SDaniel Berlin         VD.DFSIn = DomNode->getDFSNumIn();
642439042b7SDaniel Berlin         VD.DFSOut = DomNode->getDFSNumOut();
643439042b7SDaniel Berlin         VD.PInfo = PossibleCopy;
644439042b7SDaniel Berlin         OrderedUses.push_back(VD);
645fccbda96SDaniel Berlin       } else if (isa<PredicateWithEdge>(PossibleCopy)) {
646dbe8264cSDaniel Berlin         // If we can only do phi uses, we treat it like it's in the branch
647dbe8264cSDaniel Berlin         // block, and handle it specially. We know that it goes last, and only
648dbe8264cSDaniel Berlin         // dominate phi uses.
649fccbda96SDaniel Berlin         auto BlockEdge = getBlockEdge(PossibleCopy);
650fccbda96SDaniel Berlin         if (EdgeUsesOnly.count(BlockEdge)) {
651dbe8264cSDaniel Berlin           VD.LocalNum = LN_Last;
652fccbda96SDaniel Berlin           auto *DomNode = DT.getNode(BlockEdge.first);
653dbe8264cSDaniel Berlin           if (DomNode) {
654dbe8264cSDaniel Berlin             VD.DFSIn = DomNode->getDFSNumIn();
655dbe8264cSDaniel Berlin             VD.DFSOut = DomNode->getDFSNumOut();
656dbe8264cSDaniel Berlin             VD.PInfo = PossibleCopy;
657588e0be3SDaniel Berlin             VD.EdgeOnly = true;
658dbe8264cSDaniel Berlin             OrderedUses.push_back(VD);
659dbe8264cSDaniel Berlin           }
660dbe8264cSDaniel Berlin         } else {
661dbe8264cSDaniel Berlin           // Otherwise, we are in the split block (even though we perform
662dbe8264cSDaniel Berlin           // insertion in the branch block).
663dbe8264cSDaniel Berlin           // Insert a possible copy at the split block and before the branch.
664dbe8264cSDaniel Berlin           VD.LocalNum = LN_First;
665fccbda96SDaniel Berlin           auto *DomNode = DT.getNode(BlockEdge.second);
666dbe8264cSDaniel Berlin           if (DomNode) {
667dbe8264cSDaniel Berlin             VD.DFSIn = DomNode->getDFSNumIn();
668dbe8264cSDaniel Berlin             VD.DFSOut = DomNode->getDFSNumOut();
669dbe8264cSDaniel Berlin             VD.PInfo = PossibleCopy;
670dbe8264cSDaniel Berlin             OrderedUses.push_back(VD);
671dbe8264cSDaniel Berlin           }
672dbe8264cSDaniel Berlin         }
673dbe8264cSDaniel Berlin       }
674439042b7SDaniel Berlin     }
675439042b7SDaniel Berlin 
676439042b7SDaniel Berlin     convertUsesToDFSOrdered(Op, OrderedUses);
677e6bb6635SMandeep Singh Grang     // Here we require a stable sort because we do not bother to try to
678e6bb6635SMandeep Singh Grang     // assign an order to the operands the uses represent. Thus, two
679e6bb6635SMandeep Singh Grang     // uses in the same instruction do not have a strict sort order
680e6bb6635SMandeep Singh Grang     // currently and will be considered equal. We could get rid of the
681e6bb6635SMandeep Singh Grang     // stable sort by creating one if we wanted.
682efd94c56SFangrui Song     llvm::stable_sort(OrderedUses, Compare);
683439042b7SDaniel Berlin     SmallVector<ValueDFS, 8> RenameStack;
684439042b7SDaniel Berlin     // For each use, sorted into dfs order, push values and replaces uses with
685439042b7SDaniel Berlin     // top of stack, which will represent the reaching def.
686439042b7SDaniel Berlin     for (auto &VD : OrderedUses) {
687439042b7SDaniel Berlin       // We currently do not materialize copy over copy, but we should decide if
688439042b7SDaniel Berlin       // we want to.
689439042b7SDaniel Berlin       bool PossibleCopy = VD.PInfo != nullptr;
690439042b7SDaniel Berlin       if (RenameStack.empty()) {
691d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Rename Stack is empty\n");
692439042b7SDaniel Berlin       } else {
693d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Rename Stack Top DFS numbers are ("
694439042b7SDaniel Berlin                           << RenameStack.back().DFSIn << ","
695439042b7SDaniel Berlin                           << RenameStack.back().DFSOut << ")\n");
696439042b7SDaniel Berlin       }
697439042b7SDaniel Berlin 
698d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Current DFS numbers are (" << VD.DFSIn << ","
699439042b7SDaniel Berlin                         << VD.DFSOut << ")\n");
700439042b7SDaniel Berlin 
701439042b7SDaniel Berlin       bool ShouldPush = (VD.Def || PossibleCopy);
702dbe8264cSDaniel Berlin       bool OutOfScope = !stackIsInScope(RenameStack, VD);
703439042b7SDaniel Berlin       if (OutOfScope || ShouldPush) {
704439042b7SDaniel Berlin         // Sync to our current scope.
705dbe8264cSDaniel Berlin         popStackUntilDFSScope(RenameStack, VD);
706439042b7SDaniel Berlin         if (ShouldPush) {
707439042b7SDaniel Berlin           RenameStack.push_back(VD);
708439042b7SDaniel Berlin         }
709439042b7SDaniel Berlin       }
710439042b7SDaniel Berlin       // If we get to this point, and the stack is empty we must have a use
711439042b7SDaniel Berlin       // with no renaming needed, just skip it.
712439042b7SDaniel Berlin       if (RenameStack.empty())
713439042b7SDaniel Berlin         continue;
714439042b7SDaniel Berlin       // Skip values, only want to rename the uses
715439042b7SDaniel Berlin       if (VD.Def || PossibleCopy)
716439042b7SDaniel Berlin         continue;
717a4b5c01dSDaniel Berlin       if (!DebugCounter::shouldExecute(RenameCounter)) {
718d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Skipping execution due to debug counter\n");
719a4b5c01dSDaniel Berlin         continue;
720a4b5c01dSDaniel Berlin       }
721439042b7SDaniel Berlin       ValueDFS &Result = RenameStack.back();
722439042b7SDaniel Berlin 
723439042b7SDaniel Berlin       // If the possible copy dominates something, materialize our stack up to
724439042b7SDaniel Berlin       // this point. This ensures every comparison that affects our operation
725439042b7SDaniel Berlin       // ends up with predicateinfo.
726439042b7SDaniel Berlin       if (!Result.Def)
727439042b7SDaniel Berlin         Result.Def = materializeStack(Counter, RenameStack, Op);
728439042b7SDaniel Berlin 
729d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Found replacement " << *Result.Def << " for "
730d34e60caSNicola Zaghen                         << *VD.U->get() << " in " << *(VD.U->getUser())
731d34e60caSNicola Zaghen                         << "\n");
732c763fd1aSDaniel Berlin       assert(DT.dominates(cast<Instruction>(Result.Def), *VD.U) &&
733439042b7SDaniel Berlin              "Predicateinfo def should have dominated this use");
734c763fd1aSDaniel Berlin       VD.U->set(Result.Def);
735439042b7SDaniel Berlin     }
736439042b7SDaniel Berlin   }
737439042b7SDaniel Berlin }
738439042b7SDaniel Berlin 
739a42fd18dSNikita Popov PredicateInfoBuilder::ValueInfo &
getOrCreateValueInfo(Value * Operand)740a42fd18dSNikita Popov PredicateInfoBuilder::getOrCreateValueInfo(Value *Operand) {
741439042b7SDaniel Berlin   auto OIN = ValueInfoNums.find(Operand);
742439042b7SDaniel Berlin   if (OIN == ValueInfoNums.end()) {
743439042b7SDaniel Berlin     // This will grow it
744439042b7SDaniel Berlin     ValueInfos.resize(ValueInfos.size() + 1);
745439042b7SDaniel Berlin     // This will use the new size and give us a 0 based number of the info
746439042b7SDaniel Berlin     auto InsertResult = ValueInfoNums.insert({Operand, ValueInfos.size() - 1});
747439042b7SDaniel Berlin     assert(InsertResult.second && "Value info number already existed?");
748439042b7SDaniel Berlin     return ValueInfos[InsertResult.first->second];
749439042b7SDaniel Berlin   }
750439042b7SDaniel Berlin   return ValueInfos[OIN->second];
751439042b7SDaniel Berlin }
752439042b7SDaniel Berlin 
753a42fd18dSNikita Popov const PredicateInfoBuilder::ValueInfo &
getValueInfo(Value * Operand) const754a42fd18dSNikita Popov PredicateInfoBuilder::getValueInfo(Value *Operand) const {
755439042b7SDaniel Berlin   auto OINI = ValueInfoNums.lookup(Operand);
756439042b7SDaniel Berlin   assert(OINI != 0 && "Operand was not really in the Value Info Numbers");
757439042b7SDaniel Berlin   assert(OINI < ValueInfos.size() &&
758439042b7SDaniel Berlin          "Value Info Number greater than size of Value Info Table");
759439042b7SDaniel Berlin   return ValueInfos[OINI];
760439042b7SDaniel Berlin }
761439042b7SDaniel Berlin 
PredicateInfo(Function & F,DominatorTree & DT,AssumptionCache & AC)762439042b7SDaniel Berlin PredicateInfo::PredicateInfo(Function &F, DominatorTree &DT,
763439042b7SDaniel Berlin                              AssumptionCache &AC)
764a42fd18dSNikita Popov     : F(F) {
765a42fd18dSNikita Popov   PredicateInfoBuilder Builder(*this, F, DT, AC);
766a42fd18dSNikita Popov   Builder.buildPredicateInfo();
767439042b7SDaniel Berlin }
768439042b7SDaniel Berlin 
769dc5570d1SJeroen Dobbelaere // Remove all declarations we created . The PredicateInfo consumers are
770dc5570d1SJeroen Dobbelaere // responsible for remove the ssa_copy calls created.
~PredicateInfo()771dc5570d1SJeroen Dobbelaere PredicateInfo::~PredicateInfo() {
772dc5570d1SJeroen Dobbelaere   // Collect function pointers in set first, as SmallSet uses a SmallVector
773dc5570d1SJeroen Dobbelaere   // internally and we have to remove the asserting value handles first.
774dc5570d1SJeroen Dobbelaere   SmallPtrSet<Function *, 20> FunctionPtrs;
775dc5570d1SJeroen Dobbelaere   for (auto &F : CreatedDeclarations)
776dc5570d1SJeroen Dobbelaere     FunctionPtrs.insert(&*F);
777dc5570d1SJeroen Dobbelaere   CreatedDeclarations.clear();
778dc5570d1SJeroen Dobbelaere 
779dc5570d1SJeroen Dobbelaere   for (Function *F : FunctionPtrs) {
780dc5570d1SJeroen Dobbelaere     assert(F->user_begin() == F->user_end() &&
781dc5570d1SJeroen Dobbelaere            "PredicateInfo consumer did not remove all SSA copies.");
782dc5570d1SJeroen Dobbelaere     F->eraseFromParent();
783dc5570d1SJeroen Dobbelaere   }
784dc5570d1SJeroen Dobbelaere }
785dc5570d1SJeroen Dobbelaere 
getConstraint() const786c6e13667SNikita Popov Optional<PredicateConstraint> PredicateBase::getConstraint() const {
787c6e13667SNikita Popov   switch (Type) {
788c6e13667SNikita Popov   case PT_Assume:
789c6e13667SNikita Popov   case PT_Branch: {
790c6e13667SNikita Popov     bool TrueEdge = true;
791c6e13667SNikita Popov     if (auto *PBranch = dyn_cast<PredicateBranch>(this))
792c6e13667SNikita Popov       TrueEdge = PBranch->TrueEdge;
793c6e13667SNikita Popov 
794c6e13667SNikita Popov     if (Condition == RenamedOp) {
795c6e13667SNikita Popov       return {{CmpInst::ICMP_EQ,
796c6e13667SNikita Popov                TrueEdge ? ConstantInt::getTrue(Condition->getType())
797c6e13667SNikita Popov                         : ConstantInt::getFalse(Condition->getType())}};
798c6e13667SNikita Popov     }
799c6e13667SNikita Popov 
800c6e13667SNikita Popov     CmpInst *Cmp = dyn_cast<CmpInst>(Condition);
801def48b0eSNikita Popov     if (!Cmp) {
802def48b0eSNikita Popov       // TODO: Make this an assertion once RenamedOp is fully accurate.
803def48b0eSNikita Popov       return None;
804def48b0eSNikita Popov     }
805c6e13667SNikita Popov 
806c6e13667SNikita Popov     CmpInst::Predicate Pred;
807c6e13667SNikita Popov     Value *OtherOp;
808c6e13667SNikita Popov     if (Cmp->getOperand(0) == RenamedOp) {
809c6e13667SNikita Popov       Pred = Cmp->getPredicate();
810c6e13667SNikita Popov       OtherOp = Cmp->getOperand(1);
811c6e13667SNikita Popov     } else if (Cmp->getOperand(1) == RenamedOp) {
812c6e13667SNikita Popov       Pred = Cmp->getSwappedPredicate();
813c6e13667SNikita Popov       OtherOp = Cmp->getOperand(0);
814c6e13667SNikita Popov     } else {
815c6e13667SNikita Popov       // TODO: Make this an assertion once RenamedOp is fully accurate.
816c6e13667SNikita Popov       return None;
817c6e13667SNikita Popov     }
818c6e13667SNikita Popov 
819c6e13667SNikita Popov     // Invert predicate along false edge.
820c6e13667SNikita Popov     if (!TrueEdge)
821c6e13667SNikita Popov       Pred = CmpInst::getInversePredicate(Pred);
822c6e13667SNikita Popov 
823c6e13667SNikita Popov     return {{Pred, OtherOp}};
824c6e13667SNikita Popov   }
825c6e13667SNikita Popov   case PT_Switch:
826c6e13667SNikita Popov     if (Condition != RenamedOp) {
827c6e13667SNikita Popov       // TODO: Make this an assertion once RenamedOp is fully accurate.
828c6e13667SNikita Popov       return None;
829c6e13667SNikita Popov     }
830c6e13667SNikita Popov 
831c6e13667SNikita Popov     return {{CmpInst::ICMP_EQ, cast<PredicateSwitch>(this)->CaseValue}};
832c6e13667SNikita Popov   }
833c6e13667SNikita Popov   llvm_unreachable("Unknown predicate type");
834c6e13667SNikita Popov }
835c6e13667SNikita Popov 
verifyPredicateInfo() const836439042b7SDaniel Berlin void PredicateInfo::verifyPredicateInfo() const {}
837439042b7SDaniel Berlin 
838439042b7SDaniel Berlin char PredicateInfoPrinterLegacyPass::ID = 0;
839439042b7SDaniel Berlin 
PredicateInfoPrinterLegacyPass()840439042b7SDaniel Berlin PredicateInfoPrinterLegacyPass::PredicateInfoPrinterLegacyPass()
841439042b7SDaniel Berlin     : FunctionPass(ID) {
842439042b7SDaniel Berlin   initializePredicateInfoPrinterLegacyPassPass(
843439042b7SDaniel Berlin       *PassRegistry::getPassRegistry());
844439042b7SDaniel Berlin }
845439042b7SDaniel Berlin 
getAnalysisUsage(AnalysisUsage & AU) const846439042b7SDaniel Berlin void PredicateInfoPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
847439042b7SDaniel Berlin   AU.setPreservesAll();
848439042b7SDaniel Berlin   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
849439042b7SDaniel Berlin   AU.addRequired<AssumptionCacheTracker>();
850439042b7SDaniel Berlin }
851439042b7SDaniel Berlin 
852dc5570d1SJeroen Dobbelaere // Replace ssa_copy calls created by PredicateInfo with their operand.
replaceCreatedSSACopys(PredicateInfo & PredInfo,Function & F)853dc5570d1SJeroen Dobbelaere static void replaceCreatedSSACopys(PredicateInfo &PredInfo, Function &F) {
854dc5570d1SJeroen Dobbelaere   for (Instruction &Inst : llvm::make_early_inc_range(instructions(F))) {
855dc5570d1SJeroen Dobbelaere     const auto *PI = PredInfo.getPredicateInfoFor(&Inst);
856dc5570d1SJeroen Dobbelaere     auto *II = dyn_cast<IntrinsicInst>(&Inst);
857dc5570d1SJeroen Dobbelaere     if (!PI || !II || II->getIntrinsicID() != Intrinsic::ssa_copy)
858dc5570d1SJeroen Dobbelaere       continue;
859dc5570d1SJeroen Dobbelaere 
860dc5570d1SJeroen Dobbelaere     Inst.replaceAllUsesWith(II->getOperand(0));
861dc5570d1SJeroen Dobbelaere     Inst.eraseFromParent();
862dc5570d1SJeroen Dobbelaere   }
863dc5570d1SJeroen Dobbelaere }
864dc5570d1SJeroen Dobbelaere 
runOnFunction(Function & F)865439042b7SDaniel Berlin bool PredicateInfoPrinterLegacyPass::runOnFunction(Function &F) {
866439042b7SDaniel Berlin   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
867439042b7SDaniel Berlin   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8680eaee545SJonas Devlieghere   auto PredInfo = std::make_unique<PredicateInfo>(F, DT, AC);
869439042b7SDaniel Berlin   PredInfo->print(dbgs());
870439042b7SDaniel Berlin   if (VerifyPredicateInfo)
871439042b7SDaniel Berlin     PredInfo->verifyPredicateInfo();
872dc5570d1SJeroen Dobbelaere 
873dc5570d1SJeroen Dobbelaere   replaceCreatedSSACopys(*PredInfo, F);
874439042b7SDaniel Berlin   return false;
875439042b7SDaniel Berlin }
876439042b7SDaniel Berlin 
run(Function & F,FunctionAnalysisManager & AM)877439042b7SDaniel Berlin PreservedAnalyses PredicateInfoPrinterPass::run(Function &F,
878439042b7SDaniel Berlin                                                 FunctionAnalysisManager &AM) {
879439042b7SDaniel Berlin   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
880439042b7SDaniel Berlin   auto &AC = AM.getResult<AssumptionAnalysis>(F);
881439042b7SDaniel Berlin   OS << "PredicateInfo for function: " << F.getName() << "\n";
8820eaee545SJonas Devlieghere   auto PredInfo = std::make_unique<PredicateInfo>(F, DT, AC);
88336d2e25dSFlorian Hahn   PredInfo->print(OS);
884439042b7SDaniel Berlin 
885dc5570d1SJeroen Dobbelaere   replaceCreatedSSACopys(*PredInfo, F);
886439042b7SDaniel Berlin   return PreservedAnalyses::all();
887439042b7SDaniel Berlin }
888439042b7SDaniel Berlin 
8895f8f34e4SAdrian Prantl /// An assembly annotator class to print PredicateInfo information in
890439042b7SDaniel Berlin /// comments.
891439042b7SDaniel Berlin class PredicateInfoAnnotatedWriter : public AssemblyAnnotationWriter {
892439042b7SDaniel Berlin   friend class PredicateInfo;
893439042b7SDaniel Berlin   const PredicateInfo *PredInfo;
894439042b7SDaniel Berlin 
895439042b7SDaniel Berlin public:
PredicateInfoAnnotatedWriter(const PredicateInfo * M)896439042b7SDaniel Berlin   PredicateInfoAnnotatedWriter(const PredicateInfo *M) : PredInfo(M) {}
897439042b7SDaniel Berlin 
emitBasicBlockStartAnnot(const BasicBlock * BB,formatted_raw_ostream & OS)898a19461d9SLogan Smith   void emitBasicBlockStartAnnot(const BasicBlock *BB,
899a19461d9SLogan Smith                                 formatted_raw_ostream &OS) override {}
900439042b7SDaniel Berlin 
emitInstructionAnnot(const Instruction * I,formatted_raw_ostream & OS)901a19461d9SLogan Smith   void emitInstructionAnnot(const Instruction *I,
902a19461d9SLogan Smith                             formatted_raw_ostream &OS) override {
903439042b7SDaniel Berlin     if (const auto *PI = PredInfo->getPredicateInfoFor(I)) {
904439042b7SDaniel Berlin       OS << "; Has predicate info\n";
905fccbda96SDaniel Berlin       if (const auto *PB = dyn_cast<PredicateBranch>(PI)) {
906439042b7SDaniel Berlin         OS << "; branch predicate info { TrueEdge: " << PB->TrueEdge
907fccbda96SDaniel Berlin            << " Comparison:" << *PB->Condition << " Edge: [";
908fccbda96SDaniel Berlin         PB->From->printAsOperand(OS);
909fccbda96SDaniel Berlin         OS << ",";
910fccbda96SDaniel Berlin         PB->To->printAsOperand(OS);
911c0308fd1SNikita Popov         OS << "]";
912fccbda96SDaniel Berlin       } else if (const auto *PS = dyn_cast<PredicateSwitch>(PI)) {
913fccbda96SDaniel Berlin         OS << "; switch predicate info { CaseValue: " << *PS->CaseValue
914fccbda96SDaniel Berlin            << " Switch:" << *PS->Switch << " Edge: [";
915fccbda96SDaniel Berlin         PS->From->printAsOperand(OS);
916fccbda96SDaniel Berlin         OS << ",";
917fccbda96SDaniel Berlin         PS->To->printAsOperand(OS);
918c0308fd1SNikita Popov         OS << "]";
919fccbda96SDaniel Berlin       } else if (const auto *PA = dyn_cast<PredicateAssume>(PI)) {
920439042b7SDaniel Berlin         OS << "; assume predicate info {"
921c0308fd1SNikita Popov            << " Comparison:" << *PA->Condition;
922439042b7SDaniel Berlin       }
923c0308fd1SNikita Popov       OS << ", RenamedOp: ";
924c0308fd1SNikita Popov       PI->RenamedOp->printAsOperand(OS, false);
925c0308fd1SNikita Popov       OS << " }\n";
926439042b7SDaniel Berlin     }
927fccbda96SDaniel Berlin   }
928439042b7SDaniel Berlin };
929439042b7SDaniel Berlin 
print(raw_ostream & OS) const930439042b7SDaniel Berlin void PredicateInfo::print(raw_ostream &OS) const {
931439042b7SDaniel Berlin   PredicateInfoAnnotatedWriter Writer(this);
932439042b7SDaniel Berlin   F.print(OS, &Writer);
933439042b7SDaniel Berlin }
934439042b7SDaniel Berlin 
dump() const935439042b7SDaniel Berlin void PredicateInfo::dump() const {
936439042b7SDaniel Berlin   PredicateInfoAnnotatedWriter Writer(this);
937439042b7SDaniel Berlin   F.print(dbgs(), &Writer);
938439042b7SDaniel Berlin }
939439042b7SDaniel Berlin 
run(Function & F,FunctionAnalysisManager & AM)940439042b7SDaniel Berlin PreservedAnalyses PredicateInfoVerifierPass::run(Function &F,
941439042b7SDaniel Berlin                                                  FunctionAnalysisManager &AM) {
942439042b7SDaniel Berlin   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
943439042b7SDaniel Berlin   auto &AC = AM.getResult<AssumptionAnalysis>(F);
9440eaee545SJonas Devlieghere   std::make_unique<PredicateInfo>(F, DT, AC)->verifyPredicateInfo();
945439042b7SDaniel Berlin 
946439042b7SDaniel Berlin   return PreservedAnalyses::all();
947439042b7SDaniel Berlin }
9486f1ae631SEugene Zelenko }
949