xref: /src/contrib/llvm-project/llvm/lib/Transforms/Utils/PredicateInfo.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
171d5a254SDimitry Andric //===-- PredicateInfo.cpp - PredicateInfo Builder--------------------===//
271d5a254SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
671d5a254SDimitry Andric //
771d5a254SDimitry Andric //===----------------------------------------------------------------===//
871d5a254SDimitry Andric //
971d5a254SDimitry Andric // This file implements the PredicateInfo class.
1071d5a254SDimitry Andric //
1171d5a254SDimitry Andric //===----------------------------------------------------------------===//
1271d5a254SDimitry Andric 
1371d5a254SDimitry Andric #include "llvm/Transforms/Utils/PredicateInfo.h"
1471d5a254SDimitry Andric #include "llvm/ADT/DenseMap.h"
1571d5a254SDimitry Andric #include "llvm/ADT/DepthFirstIterator.h"
1671d5a254SDimitry Andric #include "llvm/ADT/STLExtras.h"
1771d5a254SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
1871d5a254SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
1971d5a254SDimitry Andric #include "llvm/IR/AssemblyAnnotationWriter.h"
2071d5a254SDimitry Andric #include "llvm/IR/Dominators.h"
2171d5a254SDimitry Andric #include "llvm/IR/IRBuilder.h"
22c0981da4SDimitry Andric #include "llvm/IR/InstIterator.h"
2371d5a254SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
2471d5a254SDimitry Andric #include "llvm/IR/Module.h"
2571d5a254SDimitry Andric #include "llvm/IR/PatternMatch.h"
26cfca06d7SDimitry Andric #include "llvm/Support/CommandLine.h"
2771d5a254SDimitry Andric #include "llvm/Support/Debug.h"
2871d5a254SDimitry Andric #include "llvm/Support/DebugCounter.h"
2971d5a254SDimitry Andric #include "llvm/Support/FormattedStream.h"
3071d5a254SDimitry Andric #include <algorithm>
3171d5a254SDimitry Andric #define DEBUG_TYPE "predicateinfo"
3271d5a254SDimitry Andric using namespace llvm;
3371d5a254SDimitry Andric using namespace PatternMatch;
3471d5a254SDimitry Andric 
3571d5a254SDimitry Andric static cl::opt<bool> VerifyPredicateInfo(
3671d5a254SDimitry Andric     "verify-predicateinfo", cl::init(false), cl::Hidden,
3771d5a254SDimitry Andric     cl::desc("Verify PredicateInfo in legacy printer pass."));
3871d5a254SDimitry Andric DEBUG_COUNTER(RenameCounter, "predicateinfo-rename",
39044eb2f6SDimitry Andric               "Controls which variables are renamed with predicateinfo");
40044eb2f6SDimitry Andric 
41b60736ecSDimitry Andric // Maximum number of conditions considered for renaming for each branch/assume.
42b60736ecSDimitry Andric // This limits renaming of deep and/or chains.
43b60736ecSDimitry Andric static const unsigned MaxCondsPerBranch = 8;
44b60736ecSDimitry Andric 
45044eb2f6SDimitry Andric namespace {
4671d5a254SDimitry Andric // Given a predicate info that is a type of branching terminator, get the
4771d5a254SDimitry Andric // branching block.
getBranchBlock(const PredicateBase * PB)4871d5a254SDimitry Andric const BasicBlock *getBranchBlock(const PredicateBase *PB) {
4971d5a254SDimitry Andric   assert(isa<PredicateWithEdge>(PB) &&
5071d5a254SDimitry Andric          "Only branches and switches should have PHIOnly defs that "
5171d5a254SDimitry Andric          "require branch blocks.");
5271d5a254SDimitry Andric   return cast<PredicateWithEdge>(PB)->From;
5371d5a254SDimitry Andric }
5471d5a254SDimitry Andric 
5571d5a254SDimitry Andric // Given a predicate info that is a type of branching terminator, get the
5671d5a254SDimitry Andric // branching terminator.
getBranchTerminator(const PredicateBase * PB)5771d5a254SDimitry Andric static Instruction *getBranchTerminator(const PredicateBase *PB) {
5871d5a254SDimitry Andric   assert(isa<PredicateWithEdge>(PB) &&
5971d5a254SDimitry Andric          "Not a predicate info type we know how to get a terminator from.");
6071d5a254SDimitry Andric   return cast<PredicateWithEdge>(PB)->From->getTerminator();
6171d5a254SDimitry Andric }
6271d5a254SDimitry Andric 
6371d5a254SDimitry Andric // Given a predicate info that is a type of branching terminator, get the
6471d5a254SDimitry Andric // edge this predicate info represents
getBlockEdge(const PredicateBase * PB)65344a3780SDimitry Andric std::pair<BasicBlock *, BasicBlock *> getBlockEdge(const PredicateBase *PB) {
6671d5a254SDimitry Andric   assert(isa<PredicateWithEdge>(PB) &&
6771d5a254SDimitry Andric          "Not a predicate info type we know how to get an edge from.");
6871d5a254SDimitry Andric   const auto *PEdge = cast<PredicateWithEdge>(PB);
6971d5a254SDimitry Andric   return std::make_pair(PEdge->From, PEdge->To);
7071d5a254SDimitry Andric }
7171d5a254SDimitry Andric }
7271d5a254SDimitry Andric 
7371d5a254SDimitry Andric namespace llvm {
7471d5a254SDimitry Andric enum LocalNum {
7571d5a254SDimitry Andric   // Operations that must appear first in the block.
7671d5a254SDimitry Andric   LN_First,
7771d5a254SDimitry Andric   // Operations that are somewhere in the middle of the block, and are sorted on
7871d5a254SDimitry Andric   // demand.
7971d5a254SDimitry Andric   LN_Middle,
8071d5a254SDimitry Andric   // Operations that must appear last in a block, like successor phi node uses.
8171d5a254SDimitry Andric   LN_Last
8271d5a254SDimitry Andric };
8371d5a254SDimitry Andric 
8471d5a254SDimitry Andric // Associate global and local DFS info with defs and uses, so we can sort them
8571d5a254SDimitry Andric // into a global domination ordering.
8671d5a254SDimitry Andric struct ValueDFS {
8771d5a254SDimitry Andric   int DFSIn = 0;
8871d5a254SDimitry Andric   int DFSOut = 0;
8971d5a254SDimitry Andric   unsigned int LocalNum = LN_Middle;
9071d5a254SDimitry Andric   // Only one of Def or Use will be set.
9171d5a254SDimitry Andric   Value *Def = nullptr;
9271d5a254SDimitry Andric   Use *U = nullptr;
9371d5a254SDimitry Andric   // Neither PInfo nor EdgeOnly participate in the ordering
9471d5a254SDimitry Andric   PredicateBase *PInfo = nullptr;
9571d5a254SDimitry Andric   bool EdgeOnly = false;
9671d5a254SDimitry Andric };
9771d5a254SDimitry Andric 
989df3605dSDimitry Andric // Perform a strict weak ordering on instructions and arguments.
valueComesBefore(const Value * A,const Value * B)99cfca06d7SDimitry Andric static bool valueComesBefore(const Value *A, const Value *B) {
1009df3605dSDimitry Andric   auto *ArgA = dyn_cast_or_null<Argument>(A);
1019df3605dSDimitry Andric   auto *ArgB = dyn_cast_or_null<Argument>(B);
1029df3605dSDimitry Andric   if (ArgA && !ArgB)
1039df3605dSDimitry Andric     return true;
1049df3605dSDimitry Andric   if (ArgB && !ArgA)
1059df3605dSDimitry Andric     return false;
1069df3605dSDimitry Andric   if (ArgA && ArgB)
1079df3605dSDimitry Andric     return ArgA->getArgNo() < ArgB->getArgNo();
108cfca06d7SDimitry Andric   return cast<Instruction>(A)->comesBefore(cast<Instruction>(B));
1099df3605dSDimitry Andric }
1109df3605dSDimitry Andric 
111cfca06d7SDimitry Andric // This compares ValueDFS structures. Doing so allows us to walk the minimum
112cfca06d7SDimitry Andric // number of instructions necessary to compute our def/use ordering.
11371d5a254SDimitry Andric struct ValueDFS_Compare {
1141d5ae102SDimitry Andric   DominatorTree &DT;
ValueDFS_Comparellvm::ValueDFS_Compare115cfca06d7SDimitry Andric   ValueDFS_Compare(DominatorTree &DT) : DT(DT) {}
1169df3605dSDimitry Andric 
operator ()llvm::ValueDFS_Compare11771d5a254SDimitry Andric   bool operator()(const ValueDFS &A, const ValueDFS &B) const {
11871d5a254SDimitry Andric     if (&A == &B)
11971d5a254SDimitry Andric       return false;
12071d5a254SDimitry Andric     // The only case we can't directly compare them is when they in the same
12171d5a254SDimitry Andric     // block, and both have localnum == middle.  In that case, we have to use
12271d5a254SDimitry Andric     // comesbefore to see what the real ordering is, because they are in the
12371d5a254SDimitry Andric     // same basic block.
12471d5a254SDimitry Andric 
1251d5ae102SDimitry Andric     assert((A.DFSIn != B.DFSIn || A.DFSOut == B.DFSOut) &&
1261d5ae102SDimitry Andric            "Equal DFS-in numbers imply equal out numbers");
1271d5ae102SDimitry Andric     bool SameBlock = A.DFSIn == B.DFSIn;
12871d5a254SDimitry Andric 
12971d5a254SDimitry Andric     // We want to put the def that will get used for a given set of phi uses,
13071d5a254SDimitry Andric     // before those phi uses.
13171d5a254SDimitry Andric     // So we sort by edge, then by def.
13271d5a254SDimitry Andric     // Note that only phi nodes uses and defs can come last.
13371d5a254SDimitry Andric     if (SameBlock && A.LocalNum == LN_Last && B.LocalNum == LN_Last)
13471d5a254SDimitry Andric       return comparePHIRelated(A, B);
13571d5a254SDimitry Andric 
1361d5ae102SDimitry Andric     bool isADef = A.Def;
1371d5ae102SDimitry Andric     bool isBDef = B.Def;
13871d5a254SDimitry Andric     if (!SameBlock || A.LocalNum != LN_Middle || B.LocalNum != LN_Middle)
1391d5ae102SDimitry Andric       return std::tie(A.DFSIn, A.LocalNum, isADef) <
1401d5ae102SDimitry Andric              std::tie(B.DFSIn, B.LocalNum, isBDef);
14171d5a254SDimitry Andric     return localComesBefore(A, B);
14271d5a254SDimitry Andric   }
14371d5a254SDimitry Andric 
14471d5a254SDimitry Andric   // For a phi use, or a non-materialized def, return the edge it represents.
getBlockEdgellvm::ValueDFS_Compare145344a3780SDimitry Andric   std::pair<BasicBlock *, BasicBlock *> getBlockEdge(const ValueDFS &VD) const {
14671d5a254SDimitry Andric     if (!VD.Def && VD.U) {
14771d5a254SDimitry Andric       auto *PHI = cast<PHINode>(VD.U->getUser());
14871d5a254SDimitry Andric       return std::make_pair(PHI->getIncomingBlock(*VD.U), PHI->getParent());
14971d5a254SDimitry Andric     }
15071d5a254SDimitry Andric     // This is really a non-materialized def.
15171d5a254SDimitry Andric     return ::getBlockEdge(VD.PInfo);
15271d5a254SDimitry Andric   }
15371d5a254SDimitry Andric 
15471d5a254SDimitry Andric   // For two phi related values, return the ordering.
comparePHIRelatedllvm::ValueDFS_Compare15571d5a254SDimitry Andric   bool comparePHIRelated(const ValueDFS &A, const ValueDFS &B) const {
1561d5ae102SDimitry Andric     BasicBlock *ASrc, *ADest, *BSrc, *BDest;
1571d5ae102SDimitry Andric     std::tie(ASrc, ADest) = getBlockEdge(A);
1581d5ae102SDimitry Andric     std::tie(BSrc, BDest) = getBlockEdge(B);
1591d5ae102SDimitry Andric 
1601d5ae102SDimitry Andric #ifndef NDEBUG
1611d5ae102SDimitry Andric     // This function should only be used for values in the same BB, check that.
1621d5ae102SDimitry Andric     DomTreeNode *DomASrc = DT.getNode(ASrc);
1631d5ae102SDimitry Andric     DomTreeNode *DomBSrc = DT.getNode(BSrc);
1641d5ae102SDimitry Andric     assert(DomASrc->getDFSNumIn() == (unsigned)A.DFSIn &&
1651d5ae102SDimitry Andric            "DFS numbers for A should match the ones of the source block");
1661d5ae102SDimitry Andric     assert(DomBSrc->getDFSNumIn() == (unsigned)B.DFSIn &&
1671d5ae102SDimitry Andric            "DFS numbers for B should match the ones of the source block");
1681d5ae102SDimitry Andric     assert(A.DFSIn == B.DFSIn && "Values must be in the same block");
1691d5ae102SDimitry Andric #endif
1701d5ae102SDimitry Andric     (void)ASrc;
1711d5ae102SDimitry Andric     (void)BSrc;
1721d5ae102SDimitry Andric 
1731d5ae102SDimitry Andric     // Use DFS numbers to compare destination blocks, to guarantee a
1741d5ae102SDimitry Andric     // deterministic order.
1751d5ae102SDimitry Andric     DomTreeNode *DomADest = DT.getNode(ADest);
1761d5ae102SDimitry Andric     DomTreeNode *DomBDest = DT.getNode(BDest);
1771d5ae102SDimitry Andric     unsigned AIn = DomADest->getDFSNumIn();
1781d5ae102SDimitry Andric     unsigned BIn = DomBDest->getDFSNumIn();
1791d5ae102SDimitry Andric     bool isADef = A.Def;
1801d5ae102SDimitry Andric     bool isBDef = B.Def;
1811d5ae102SDimitry Andric     assert((!A.Def || !A.U) && (!B.Def || !B.U) &&
1821d5ae102SDimitry Andric            "Def and U cannot be set at the same time");
1831d5ae102SDimitry Andric     // Now sort by edge destination and then defs before uses.
1841d5ae102SDimitry Andric     return std::tie(AIn, isADef) < std::tie(BIn, isBDef);
18571d5a254SDimitry Andric   }
18671d5a254SDimitry Andric 
18771d5a254SDimitry Andric   // Get the definition of an instruction that occurs in the middle of a block.
getMiddleDefllvm::ValueDFS_Compare18871d5a254SDimitry Andric   Value *getMiddleDef(const ValueDFS &VD) const {
18971d5a254SDimitry Andric     if (VD.Def)
19071d5a254SDimitry Andric       return VD.Def;
19171d5a254SDimitry Andric     // It's possible for the defs and uses to be null.  For branches, the local
19271d5a254SDimitry Andric     // numbering will say the placed predicaeinfos should go first (IE
19371d5a254SDimitry Andric     // LN_beginning), so we won't be in this function. For assumes, we will end
19471d5a254SDimitry Andric     // up here, beause we need to order the def we will place relative to the
195cfca06d7SDimitry Andric     // assume.  So for the purpose of ordering, we pretend the def is right
196cfca06d7SDimitry Andric     // after the assume, because that is where we will insert the info.
19771d5a254SDimitry Andric     if (!VD.U) {
19871d5a254SDimitry Andric       assert(VD.PInfo &&
19971d5a254SDimitry Andric              "No def, no use, and no predicateinfo should not occur");
20071d5a254SDimitry Andric       assert(isa<PredicateAssume>(VD.PInfo) &&
20171d5a254SDimitry Andric              "Middle of block should only occur for assumes");
202cfca06d7SDimitry Andric       return cast<PredicateAssume>(VD.PInfo)->AssumeInst->getNextNode();
20371d5a254SDimitry Andric     }
20471d5a254SDimitry Andric     return nullptr;
20571d5a254SDimitry Andric   }
20671d5a254SDimitry Andric 
20771d5a254SDimitry Andric   // Return either the Def, if it's not null, or the user of the Use, if the def
20871d5a254SDimitry Andric   // is null.
getDefOrUserllvm::ValueDFS_Compare20971d5a254SDimitry Andric   const Instruction *getDefOrUser(const Value *Def, const Use *U) const {
21071d5a254SDimitry Andric     if (Def)
21171d5a254SDimitry Andric       return cast<Instruction>(Def);
21271d5a254SDimitry Andric     return cast<Instruction>(U->getUser());
21371d5a254SDimitry Andric   }
21471d5a254SDimitry Andric 
21571d5a254SDimitry Andric   // This performs the necessary local basic block ordering checks to tell
21671d5a254SDimitry Andric   // whether A comes before B, where both are in the same basic block.
localComesBeforellvm::ValueDFS_Compare21771d5a254SDimitry Andric   bool localComesBefore(const ValueDFS &A, const ValueDFS &B) const {
21871d5a254SDimitry Andric     auto *ADef = getMiddleDef(A);
21971d5a254SDimitry Andric     auto *BDef = getMiddleDef(B);
22071d5a254SDimitry Andric 
22171d5a254SDimitry Andric     // See if we have real values or uses. If we have real values, we are
22271d5a254SDimitry Andric     // guaranteed they are instructions or arguments. No matter what, we are
22371d5a254SDimitry Andric     // guaranteed they are in the same block if they are instructions.
22471d5a254SDimitry Andric     auto *ArgA = dyn_cast_or_null<Argument>(ADef);
22571d5a254SDimitry Andric     auto *ArgB = dyn_cast_or_null<Argument>(BDef);
22671d5a254SDimitry Andric 
2279df3605dSDimitry Andric     if (ArgA || ArgB)
228cfca06d7SDimitry Andric       return valueComesBefore(ArgA, ArgB);
22971d5a254SDimitry Andric 
23071d5a254SDimitry Andric     auto *AInst = getDefOrUser(ADef, A.U);
23171d5a254SDimitry Andric     auto *BInst = getDefOrUser(BDef, B.U);
232cfca06d7SDimitry Andric     return valueComesBefore(AInst, BInst);
23371d5a254SDimitry Andric   }
23471d5a254SDimitry Andric };
23571d5a254SDimitry Andric 
236cfca06d7SDimitry Andric class PredicateInfoBuilder {
237cfca06d7SDimitry Andric   // Used to store information about each value we might rename.
238cfca06d7SDimitry Andric   struct ValueInfo {
239cfca06d7SDimitry Andric     SmallVector<PredicateBase *, 4> Infos;
240cfca06d7SDimitry Andric   };
24171d5a254SDimitry Andric 
242cfca06d7SDimitry Andric   PredicateInfo &PI;
243cfca06d7SDimitry Andric   Function &F;
244cfca06d7SDimitry Andric   DominatorTree &DT;
245cfca06d7SDimitry Andric   AssumptionCache &AC;
246cfca06d7SDimitry Andric 
247cfca06d7SDimitry Andric   // This stores info about each operand or comparison result we make copies
248cfca06d7SDimitry Andric   // of. The real ValueInfos start at index 1, index 0 is unused so that we
249cfca06d7SDimitry Andric   // can more easily detect invalid indexing.
250cfca06d7SDimitry Andric   SmallVector<ValueInfo, 32> ValueInfos;
251cfca06d7SDimitry Andric 
252cfca06d7SDimitry Andric   // This gives the index into the ValueInfos array for a given Value. Because
253cfca06d7SDimitry Andric   // 0 is not a valid Value Info index, you can use DenseMap::lookup and tell
254cfca06d7SDimitry Andric   // whether it returned a valid result.
255cfca06d7SDimitry Andric   DenseMap<Value *, unsigned int> ValueInfoNums;
256cfca06d7SDimitry Andric 
257cfca06d7SDimitry Andric   // The set of edges along which we can only handle phi uses, due to critical
258cfca06d7SDimitry Andric   // edges.
259cfca06d7SDimitry Andric   DenseSet<std::pair<BasicBlock *, BasicBlock *>> EdgeUsesOnly;
260cfca06d7SDimitry Andric 
261cfca06d7SDimitry Andric   ValueInfo &getOrCreateValueInfo(Value *);
262cfca06d7SDimitry Andric   const ValueInfo &getValueInfo(Value *) const;
263cfca06d7SDimitry Andric 
264cfca06d7SDimitry Andric   void processAssume(IntrinsicInst *, BasicBlock *,
265cfca06d7SDimitry Andric                      SmallVectorImpl<Value *> &OpsToRename);
266cfca06d7SDimitry Andric   void processBranch(BranchInst *, BasicBlock *,
267cfca06d7SDimitry Andric                      SmallVectorImpl<Value *> &OpsToRename);
268cfca06d7SDimitry Andric   void processSwitch(SwitchInst *, BasicBlock *,
269cfca06d7SDimitry Andric                      SmallVectorImpl<Value *> &OpsToRename);
270cfca06d7SDimitry Andric   void renameUses(SmallVectorImpl<Value *> &OpsToRename);
271cfca06d7SDimitry Andric   void addInfoFor(SmallVectorImpl<Value *> &OpsToRename, Value *Op,
272cfca06d7SDimitry Andric                   PredicateBase *PB);
273cfca06d7SDimitry Andric 
274cfca06d7SDimitry Andric   typedef SmallVectorImpl<ValueDFS> ValueDFSStack;
275cfca06d7SDimitry Andric   void convertUsesToDFSOrdered(Value *, SmallVectorImpl<ValueDFS> &);
276cfca06d7SDimitry Andric   Value *materializeStack(unsigned int &, ValueDFSStack &, Value *);
277cfca06d7SDimitry Andric   bool stackIsInScope(const ValueDFSStack &, const ValueDFS &) const;
278cfca06d7SDimitry Andric   void popStackUntilDFSScope(ValueDFSStack &, const ValueDFS &);
279cfca06d7SDimitry Andric 
280cfca06d7SDimitry Andric public:
PredicateInfoBuilder(PredicateInfo & PI,Function & F,DominatorTree & DT,AssumptionCache & AC)281cfca06d7SDimitry Andric   PredicateInfoBuilder(PredicateInfo &PI, Function &F, DominatorTree &DT,
282cfca06d7SDimitry Andric                        AssumptionCache &AC)
283cfca06d7SDimitry Andric       : PI(PI), F(F), DT(DT), AC(AC) {
284cfca06d7SDimitry Andric     // Push an empty operand info so that we can detect 0 as not finding one
285cfca06d7SDimitry Andric     ValueInfos.resize(1);
286cfca06d7SDimitry Andric   }
287cfca06d7SDimitry Andric 
288cfca06d7SDimitry Andric   void buildPredicateInfo();
289cfca06d7SDimitry Andric };
290cfca06d7SDimitry Andric 
stackIsInScope(const ValueDFSStack & Stack,const ValueDFS & VDUse) const291cfca06d7SDimitry Andric bool PredicateInfoBuilder::stackIsInScope(const ValueDFSStack &Stack,
29271d5a254SDimitry Andric                                           const ValueDFS &VDUse) const {
29371d5a254SDimitry Andric   if (Stack.empty())
29471d5a254SDimitry Andric     return false;
29571d5a254SDimitry Andric   // If it's a phi only use, make sure it's for this phi node edge, and that the
29671d5a254SDimitry Andric   // use is in a phi node.  If it's anything else, and the top of the stack is
29771d5a254SDimitry Andric   // EdgeOnly, we need to pop the stack.  We deliberately sort phi uses next to
29871d5a254SDimitry Andric   // the defs they must go with so that we can know it's time to pop the stack
29971d5a254SDimitry Andric   // when we hit the end of the phi uses for a given def.
30071d5a254SDimitry Andric   if (Stack.back().EdgeOnly) {
30171d5a254SDimitry Andric     if (!VDUse.U)
30271d5a254SDimitry Andric       return false;
30371d5a254SDimitry Andric     auto *PHI = dyn_cast<PHINode>(VDUse.U->getUser());
30471d5a254SDimitry Andric     if (!PHI)
30571d5a254SDimitry Andric       return false;
30671d5a254SDimitry Andric     // Check edge
30771d5a254SDimitry Andric     BasicBlock *EdgePred = PHI->getIncomingBlock(*VDUse.U);
30871d5a254SDimitry Andric     if (EdgePred != getBranchBlock(Stack.back().PInfo))
30971d5a254SDimitry Andric       return false;
31071d5a254SDimitry Andric 
31171d5a254SDimitry Andric     // Use dominates, which knows how to handle edge dominance.
31271d5a254SDimitry Andric     return DT.dominates(getBlockEdge(Stack.back().PInfo), *VDUse.U);
31371d5a254SDimitry Andric   }
31471d5a254SDimitry Andric 
31571d5a254SDimitry Andric   return (VDUse.DFSIn >= Stack.back().DFSIn &&
31671d5a254SDimitry Andric           VDUse.DFSOut <= Stack.back().DFSOut);
31771d5a254SDimitry Andric }
31871d5a254SDimitry Andric 
popStackUntilDFSScope(ValueDFSStack & Stack,const ValueDFS & VD)319cfca06d7SDimitry Andric void PredicateInfoBuilder::popStackUntilDFSScope(ValueDFSStack &Stack,
32071d5a254SDimitry Andric                                                  const ValueDFS &VD) {
32171d5a254SDimitry Andric   while (!Stack.empty() && !stackIsInScope(Stack, VD))
32271d5a254SDimitry Andric     Stack.pop_back();
32371d5a254SDimitry Andric }
32471d5a254SDimitry Andric 
32571d5a254SDimitry Andric // Convert the uses of Op into a vector of uses, associating global and local
32671d5a254SDimitry Andric // DFS info with each one.
convertUsesToDFSOrdered(Value * Op,SmallVectorImpl<ValueDFS> & DFSOrderedSet)327cfca06d7SDimitry Andric void PredicateInfoBuilder::convertUsesToDFSOrdered(
32871d5a254SDimitry Andric     Value *Op, SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
32971d5a254SDimitry Andric   for (auto &U : Op->uses()) {
33071d5a254SDimitry Andric     if (auto *I = dyn_cast<Instruction>(U.getUser())) {
33171d5a254SDimitry Andric       ValueDFS VD;
33271d5a254SDimitry Andric       // Put the phi node uses in the incoming block.
33371d5a254SDimitry Andric       BasicBlock *IBlock;
33471d5a254SDimitry Andric       if (auto *PN = dyn_cast<PHINode>(I)) {
33571d5a254SDimitry Andric         IBlock = PN->getIncomingBlock(U);
33671d5a254SDimitry Andric         // Make phi node users appear last in the incoming block
33771d5a254SDimitry Andric         // they are from.
33871d5a254SDimitry Andric         VD.LocalNum = LN_Last;
33971d5a254SDimitry Andric       } else {
34071d5a254SDimitry Andric         // If it's not a phi node use, it is somewhere in the middle of the
34171d5a254SDimitry Andric         // block.
34271d5a254SDimitry Andric         IBlock = I->getParent();
34371d5a254SDimitry Andric         VD.LocalNum = LN_Middle;
34471d5a254SDimitry Andric       }
34571d5a254SDimitry Andric       DomTreeNode *DomNode = DT.getNode(IBlock);
34671d5a254SDimitry Andric       // It's possible our use is in an unreachable block. Skip it if so.
34771d5a254SDimitry Andric       if (!DomNode)
34871d5a254SDimitry Andric         continue;
34971d5a254SDimitry Andric       VD.DFSIn = DomNode->getDFSNumIn();
35071d5a254SDimitry Andric       VD.DFSOut = DomNode->getDFSNumOut();
35171d5a254SDimitry Andric       VD.U = &U;
35271d5a254SDimitry Andric       DFSOrderedSet.push_back(VD);
35371d5a254SDimitry Andric     }
35471d5a254SDimitry Andric   }
35571d5a254SDimitry Andric }
35671d5a254SDimitry Andric 
shouldRename(Value * V)357b60736ecSDimitry Andric bool shouldRename(Value *V) {
358b60736ecSDimitry Andric   // Only want real values, not constants.  Additionally, operands with one use
359b60736ecSDimitry Andric   // are only being used in the comparison, which means they will not be useful
360b60736ecSDimitry Andric   // for us to consider for predicateinfo.
361b60736ecSDimitry Andric   return (isa<Instruction>(V) || isa<Argument>(V)) && !V->hasOneUse();
362b60736ecSDimitry Andric }
363b60736ecSDimitry Andric 
36471d5a254SDimitry Andric // Collect relevant operations from Comparison that we may want to insert copies
36571d5a254SDimitry Andric // for.
collectCmpOps(CmpInst * Comparison,SmallVectorImpl<Value * > & CmpOperands)36671d5a254SDimitry Andric void collectCmpOps(CmpInst *Comparison, SmallVectorImpl<Value *> &CmpOperands) {
36771d5a254SDimitry Andric   auto *Op0 = Comparison->getOperand(0);
36871d5a254SDimitry Andric   auto *Op1 = Comparison->getOperand(1);
36971d5a254SDimitry Andric   if (Op0 == Op1)
37071d5a254SDimitry Andric     return;
371b60736ecSDimitry Andric 
37271d5a254SDimitry Andric   CmpOperands.push_back(Op0);
37371d5a254SDimitry Andric   CmpOperands.push_back(Op1);
37471d5a254SDimitry Andric }
37571d5a254SDimitry Andric 
37671d5a254SDimitry Andric // 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)377cfca06d7SDimitry Andric void PredicateInfoBuilder::addInfoFor(SmallVectorImpl<Value *> &OpsToRename,
378cfca06d7SDimitry Andric                                       Value *Op, PredicateBase *PB) {
37971d5a254SDimitry Andric   auto &OperandInfo = getOrCreateValueInfo(Op);
3801d5ae102SDimitry Andric   if (OperandInfo.Infos.empty())
3811d5ae102SDimitry Andric     OpsToRename.push_back(Op);
382cfca06d7SDimitry Andric   PI.AllInfos.push_back(PB);
38371d5a254SDimitry Andric   OperandInfo.Infos.push_back(PB);
38471d5a254SDimitry Andric }
38571d5a254SDimitry Andric 
38671d5a254SDimitry Andric // Process an assume instruction and place relevant operations we want to rename
38771d5a254SDimitry Andric // into OpsToRename.
processAssume(IntrinsicInst * II,BasicBlock * AssumeBB,SmallVectorImpl<Value * > & OpsToRename)388cfca06d7SDimitry Andric void PredicateInfoBuilder::processAssume(
389cfca06d7SDimitry Andric     IntrinsicInst *II, BasicBlock *AssumeBB,
3901d5ae102SDimitry Andric     SmallVectorImpl<Value *> &OpsToRename) {
391b60736ecSDimitry Andric   SmallVector<Value *, 4> Worklist;
392b60736ecSDimitry Andric   SmallPtrSet<Value *, 4> Visited;
393b60736ecSDimitry Andric   Worklist.push_back(II->getOperand(0));
394b60736ecSDimitry Andric   while (!Worklist.empty()) {
395b60736ecSDimitry Andric     Value *Cond = Worklist.pop_back_val();
396b60736ecSDimitry Andric     if (!Visited.insert(Cond).second)
397b60736ecSDimitry Andric       continue;
398b60736ecSDimitry Andric     if (Visited.size() > MaxCondsPerBranch)
399b60736ecSDimitry Andric       break;
40071d5a254SDimitry Andric 
401b60736ecSDimitry Andric     Value *Op0, *Op1;
402b60736ecSDimitry Andric     if (match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
403b60736ecSDimitry Andric       Worklist.push_back(Op1);
404b60736ecSDimitry Andric       Worklist.push_back(Op0);
40571d5a254SDimitry Andric     }
406b60736ecSDimitry Andric 
407b60736ecSDimitry Andric     SmallVector<Value *, 4> Values;
408b60736ecSDimitry Andric     Values.push_back(Cond);
409b60736ecSDimitry Andric     if (auto *Cmp = dyn_cast<CmpInst>(Cond))
410b60736ecSDimitry Andric       collectCmpOps(Cmp, Values);
411b60736ecSDimitry Andric 
412b60736ecSDimitry Andric     for (Value *V : Values) {
413b60736ecSDimitry Andric       if (shouldRename(V)) {
414b60736ecSDimitry Andric         auto *PA = new PredicateAssume(V, II, Cond);
415b60736ecSDimitry Andric         addInfoFor(OpsToRename, V, PA);
41671d5a254SDimitry Andric       }
41771d5a254SDimitry Andric     }
41871d5a254SDimitry Andric   }
41971d5a254SDimitry Andric }
42071d5a254SDimitry Andric 
42171d5a254SDimitry Andric // Process a block terminating branch, and place relevant operations to be
42271d5a254SDimitry Andric // renamed into OpsToRename.
processBranch(BranchInst * BI,BasicBlock * BranchBB,SmallVectorImpl<Value * > & OpsToRename)423cfca06d7SDimitry Andric void PredicateInfoBuilder::processBranch(
424cfca06d7SDimitry Andric     BranchInst *BI, BasicBlock *BranchBB,
4251d5ae102SDimitry Andric     SmallVectorImpl<Value *> &OpsToRename) {
42671d5a254SDimitry Andric   BasicBlock *FirstBB = BI->getSuccessor(0);
42771d5a254SDimitry Andric   BasicBlock *SecondBB = BI->getSuccessor(1);
42871d5a254SDimitry Andric 
429b60736ecSDimitry Andric   for (BasicBlock *Succ : {FirstBB, SecondBB}) {
430b60736ecSDimitry Andric     bool TakenEdge = Succ == FirstBB;
43171d5a254SDimitry Andric     // Don't try to insert on a self-edge. This is mainly because we will
43271d5a254SDimitry Andric     // eliminate during renaming anyway.
43371d5a254SDimitry Andric     if (Succ == BranchBB)
43471d5a254SDimitry Andric       continue;
435b60736ecSDimitry Andric 
436b60736ecSDimitry Andric     SmallVector<Value *, 4> Worklist;
437b60736ecSDimitry Andric     SmallPtrSet<Value *, 4> Visited;
438b60736ecSDimitry Andric     Worklist.push_back(BI->getCondition());
439b60736ecSDimitry Andric     while (!Worklist.empty()) {
440b60736ecSDimitry Andric       Value *Cond = Worklist.pop_back_val();
441b60736ecSDimitry Andric       if (!Visited.insert(Cond).second)
44271d5a254SDimitry Andric         continue;
443b60736ecSDimitry Andric       if (Visited.size() > MaxCondsPerBranch)
444b60736ecSDimitry Andric         break;
445b60736ecSDimitry Andric 
446b60736ecSDimitry Andric       Value *Op0, *Op1;
447b60736ecSDimitry Andric       if (TakenEdge ? match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))
448b60736ecSDimitry Andric                     : match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
449b60736ecSDimitry Andric         Worklist.push_back(Op1);
450b60736ecSDimitry Andric         Worklist.push_back(Op0);
451b60736ecSDimitry Andric       }
452b60736ecSDimitry Andric 
453b60736ecSDimitry Andric       SmallVector<Value *, 4> Values;
454b60736ecSDimitry Andric       Values.push_back(Cond);
455b60736ecSDimitry Andric       if (auto *Cmp = dyn_cast<CmpInst>(Cond))
456b60736ecSDimitry Andric         collectCmpOps(Cmp, Values);
457b60736ecSDimitry Andric 
458b60736ecSDimitry Andric       for (Value *V : Values) {
459b60736ecSDimitry Andric         if (shouldRename(V)) {
46071d5a254SDimitry Andric           PredicateBase *PB =
461b60736ecSDimitry Andric               new PredicateBranch(V, BranchBB, Succ, Cond, TakenEdge);
462b60736ecSDimitry Andric           addInfoFor(OpsToRename, V, PB);
46371d5a254SDimitry Andric           if (!Succ->getSinglePredecessor())
46471d5a254SDimitry Andric             EdgeUsesOnly.insert({BranchBB, Succ});
46571d5a254SDimitry Andric         }
46671d5a254SDimitry Andric       }
46771d5a254SDimitry Andric     }
46871d5a254SDimitry Andric   }
46971d5a254SDimitry Andric }
47071d5a254SDimitry Andric // Process a block terminating switch, and place relevant operations to be
47171d5a254SDimitry Andric // renamed into OpsToRename.
processSwitch(SwitchInst * SI,BasicBlock * BranchBB,SmallVectorImpl<Value * > & OpsToRename)472cfca06d7SDimitry Andric void PredicateInfoBuilder::processSwitch(
473cfca06d7SDimitry Andric     SwitchInst *SI, BasicBlock *BranchBB,
4741d5ae102SDimitry Andric     SmallVectorImpl<Value *> &OpsToRename) {
47571d5a254SDimitry Andric   Value *Op = SI->getCondition();
47671d5a254SDimitry Andric   if ((!isa<Instruction>(Op) && !isa<Argument>(Op)) || Op->hasOneUse())
47771d5a254SDimitry Andric     return;
47871d5a254SDimitry Andric 
47971d5a254SDimitry Andric   // Remember how many outgoing edges there are to every successor.
48071d5a254SDimitry Andric   SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
481ac9a064cSDimitry Andric   for (BasicBlock *TargetBlock : successors(BranchBB))
48271d5a254SDimitry Andric     ++SwitchEdges[TargetBlock];
48371d5a254SDimitry Andric 
48471d5a254SDimitry Andric   // Now propagate info for each case value
48571d5a254SDimitry Andric   for (auto C : SI->cases()) {
48671d5a254SDimitry Andric     BasicBlock *TargetBlock = C.getCaseSuccessor();
48771d5a254SDimitry Andric     if (SwitchEdges.lookup(TargetBlock) == 1) {
48871d5a254SDimitry Andric       PredicateSwitch *PS = new PredicateSwitch(
48971d5a254SDimitry Andric           Op, SI->getParent(), TargetBlock, C.getCaseValue(), SI);
49071d5a254SDimitry Andric       addInfoFor(OpsToRename, Op, PS);
49171d5a254SDimitry Andric       if (!TargetBlock->getSinglePredecessor())
49271d5a254SDimitry Andric         EdgeUsesOnly.insert({BranchBB, TargetBlock});
49371d5a254SDimitry Andric     }
49471d5a254SDimitry Andric   }
49571d5a254SDimitry Andric }
49671d5a254SDimitry Andric 
49771d5a254SDimitry Andric // Build predicate info for our function
buildPredicateInfo()498cfca06d7SDimitry Andric void PredicateInfoBuilder::buildPredicateInfo() {
49971d5a254SDimitry Andric   DT.updateDFSNumbers();
50071d5a254SDimitry Andric   // Collect operands to rename from all conditional branch terminators, as well
50171d5a254SDimitry Andric   // as assume statements.
5021d5ae102SDimitry Andric   SmallVector<Value *, 8> OpsToRename;
503e3b55780SDimitry Andric   for (auto *DTN : depth_first(DT.getRootNode())) {
50471d5a254SDimitry Andric     BasicBlock *BranchBB = DTN->getBlock();
50571d5a254SDimitry Andric     if (auto *BI = dyn_cast<BranchInst>(BranchBB->getTerminator())) {
50671d5a254SDimitry Andric       if (!BI->isConditional())
50771d5a254SDimitry Andric         continue;
5087c7aba6eSDimitry Andric       // Can't insert conditional information if they all go to the same place.
5097c7aba6eSDimitry Andric       if (BI->getSuccessor(0) == BI->getSuccessor(1))
5107c7aba6eSDimitry Andric         continue;
51171d5a254SDimitry Andric       processBranch(BI, BranchBB, OpsToRename);
51271d5a254SDimitry Andric     } else if (auto *SI = dyn_cast<SwitchInst>(BranchBB->getTerminator())) {
51371d5a254SDimitry Andric       processSwitch(SI, BranchBB, OpsToRename);
51471d5a254SDimitry Andric     }
51571d5a254SDimitry Andric   }
51671d5a254SDimitry Andric   for (auto &Assume : AC.assumptions()) {
51771d5a254SDimitry Andric     if (auto *II = dyn_cast_or_null<IntrinsicInst>(Assume))
518e6d15924SDimitry Andric       if (DT.isReachableFromEntry(II->getParent()))
51971d5a254SDimitry Andric         processAssume(II, II->getParent(), OpsToRename);
52071d5a254SDimitry Andric   }
52171d5a254SDimitry Andric   // Now rename all our operations.
52271d5a254SDimitry Andric   renameUses(OpsToRename);
52371d5a254SDimitry Andric }
52471d5a254SDimitry Andric 
52571d5a254SDimitry Andric // Given the renaming stack, make all the operands currently on the stack real
52671d5a254SDimitry Andric // by inserting them into the IR.  Return the last operation's value.
materializeStack(unsigned int & Counter,ValueDFSStack & RenameStack,Value * OrigOp)527cfca06d7SDimitry Andric Value *PredicateInfoBuilder::materializeStack(unsigned int &Counter,
52871d5a254SDimitry Andric                                              ValueDFSStack &RenameStack,
52971d5a254SDimitry Andric                                              Value *OrigOp) {
53071d5a254SDimitry Andric   // Find the first thing we have to materialize
53171d5a254SDimitry Andric   auto RevIter = RenameStack.rbegin();
53271d5a254SDimitry Andric   for (; RevIter != RenameStack.rend(); ++RevIter)
53371d5a254SDimitry Andric     if (RevIter->Def)
53471d5a254SDimitry Andric       break;
53571d5a254SDimitry Andric 
53671d5a254SDimitry Andric   size_t Start = RevIter - RenameStack.rbegin();
53771d5a254SDimitry Andric   // The maximum number of things we should be trying to materialize at once
53871d5a254SDimitry Andric   // right now is 4, depending on if we had an assume, a branch, and both used
53971d5a254SDimitry Andric   // and of conditions.
54071d5a254SDimitry Andric   for (auto RenameIter = RenameStack.end() - Start;
54171d5a254SDimitry Andric        RenameIter != RenameStack.end(); ++RenameIter) {
54271d5a254SDimitry Andric     auto *Op =
54371d5a254SDimitry Andric         RenameIter == RenameStack.begin() ? OrigOp : (RenameIter - 1)->Def;
54471d5a254SDimitry Andric     ValueDFS &Result = *RenameIter;
54571d5a254SDimitry Andric     auto *ValInfo = Result.PInfo;
546cfca06d7SDimitry Andric     ValInfo->RenamedOp = (RenameStack.end() - Start) == RenameStack.begin()
547cfca06d7SDimitry Andric                              ? OrigOp
548cfca06d7SDimitry Andric                              : (RenameStack.end() - Start - 1)->Def;
54971d5a254SDimitry Andric     // For edge predicates, we can just place the operand in the block before
55071d5a254SDimitry Andric     // the terminator.  For assume, we have to place it right before the assume
55171d5a254SDimitry Andric     // to ensure we dominate all of our uses.  Always insert right before the
55271d5a254SDimitry Andric     // relevant instruction (terminator, assume), so that we insert in proper
55371d5a254SDimitry Andric     // order in the case of multiple predicateinfo in the same block.
554c0981da4SDimitry Andric     // The number of named values is used to detect if a new declaration was
555c0981da4SDimitry Andric     // added. If so, that declaration is tracked so that it can be removed when
556c0981da4SDimitry Andric     // the analysis is done. The corner case were a new declaration results in
557c0981da4SDimitry Andric     // a name clash and the old name being renamed is not considered as that
558c0981da4SDimitry Andric     // represents an invalid module.
55971d5a254SDimitry Andric     if (isa<PredicateWithEdge>(ValInfo)) {
56071d5a254SDimitry Andric       IRBuilder<> B(getBranchTerminator(ValInfo));
561c0981da4SDimitry Andric       auto NumDecls = F.getParent()->getNumNamedValues();
562344a3780SDimitry Andric       Function *IF = Intrinsic::getDeclaration(
563344a3780SDimitry Andric           F.getParent(), Intrinsic::ssa_copy, Op->getType());
564c0981da4SDimitry Andric       if (NumDecls != F.getParent()->getNumNamedValues())
565c0981da4SDimitry Andric         PI.CreatedDeclarations.insert(IF);
56671d5a254SDimitry Andric       CallInst *PIC =
56771d5a254SDimitry Andric           B.CreateCall(IF, Op, Op->getName() + "." + Twine(Counter++));
568cfca06d7SDimitry Andric       PI.PredicateMap.insert({PIC, ValInfo});
56971d5a254SDimitry Andric       Result.Def = PIC;
57071d5a254SDimitry Andric     } else {
57171d5a254SDimitry Andric       auto *PAssume = dyn_cast<PredicateAssume>(ValInfo);
57271d5a254SDimitry Andric       assert(PAssume &&
57371d5a254SDimitry Andric              "Should not have gotten here without it being an assume");
574cfca06d7SDimitry Andric       // Insert the predicate directly after the assume. While it also holds
575cfca06d7SDimitry Andric       // directly before it, assume(i1 true) is not a useful fact.
576cfca06d7SDimitry Andric       IRBuilder<> B(PAssume->AssumeInst->getNextNode());
577c0981da4SDimitry Andric       auto NumDecls = F.getParent()->getNumNamedValues();
578344a3780SDimitry Andric       Function *IF = Intrinsic::getDeclaration(
579344a3780SDimitry Andric           F.getParent(), Intrinsic::ssa_copy, Op->getType());
580c0981da4SDimitry Andric       if (NumDecls != F.getParent()->getNumNamedValues())
581c0981da4SDimitry Andric         PI.CreatedDeclarations.insert(IF);
58271d5a254SDimitry Andric       CallInst *PIC = B.CreateCall(IF, Op);
583cfca06d7SDimitry Andric       PI.PredicateMap.insert({PIC, ValInfo});
58471d5a254SDimitry Andric       Result.Def = PIC;
58571d5a254SDimitry Andric     }
58671d5a254SDimitry Andric   }
58771d5a254SDimitry Andric   return RenameStack.back().Def;
58871d5a254SDimitry Andric }
58971d5a254SDimitry Andric 
59071d5a254SDimitry Andric // Instead of the standard SSA renaming algorithm, which is O(Number of
59171d5a254SDimitry Andric // instructions), and walks the entire dominator tree, we walk only the defs +
59271d5a254SDimitry Andric // uses.  The standard SSA renaming algorithm does not really rely on the
59371d5a254SDimitry Andric // dominator tree except to order the stack push/pops of the renaming stacks, so
59471d5a254SDimitry Andric // that defs end up getting pushed before hitting the correct uses.  This does
59571d5a254SDimitry Andric // not require the dominator tree, only the *order* of the dominator tree. The
59671d5a254SDimitry Andric // complete and correct ordering of the defs and uses, in dominator tree is
59771d5a254SDimitry Andric // contained in the DFS numbering of the dominator tree. So we sort the defs and
59871d5a254SDimitry Andric // uses into the DFS ordering, and then just use the renaming stack as per
59971d5a254SDimitry Andric // normal, pushing when we hit a def (which is a predicateinfo instruction),
60071d5a254SDimitry Andric // popping when we are out of the dfs scope for that def, and replacing any uses
60171d5a254SDimitry Andric // with top of stack if it exists.  In order to handle liveness without
60271d5a254SDimitry Andric // propagating liveness info, we don't actually insert the predicateinfo
60371d5a254SDimitry Andric // instruction def until we see a use that it would dominate.  Once we see such
60471d5a254SDimitry Andric // a use, we materialize the predicateinfo instruction in the right place and
60571d5a254SDimitry Andric // use it.
60671d5a254SDimitry Andric //
60771d5a254SDimitry Andric // TODO: Use this algorithm to perform fast single-variable renaming in
60871d5a254SDimitry Andric // promotememtoreg and memoryssa.
renameUses(SmallVectorImpl<Value * > & OpsToRename)609cfca06d7SDimitry Andric void PredicateInfoBuilder::renameUses(SmallVectorImpl<Value *> &OpsToRename) {
610cfca06d7SDimitry Andric   ValueDFS_Compare Compare(DT);
61171d5a254SDimitry Andric   // Compute liveness, and rename in O(uses) per Op.
61271d5a254SDimitry Andric   for (auto *Op : OpsToRename) {
613eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "Visiting " << *Op << "\n");
61471d5a254SDimitry Andric     unsigned Counter = 0;
61571d5a254SDimitry Andric     SmallVector<ValueDFS, 16> OrderedUses;
61671d5a254SDimitry Andric     const auto &ValueInfo = getValueInfo(Op);
61771d5a254SDimitry Andric     // Insert the possible copies into the def/use list.
61871d5a254SDimitry Andric     // They will become real copies if we find a real use for them, and never
61971d5a254SDimitry Andric     // created otherwise.
620e3b55780SDimitry Andric     for (const auto &PossibleCopy : ValueInfo.Infos) {
62171d5a254SDimitry Andric       ValueDFS VD;
62271d5a254SDimitry Andric       // Determine where we are going to place the copy by the copy type.
62371d5a254SDimitry Andric       // The predicate info for branches always come first, they will get
62471d5a254SDimitry Andric       // materialized in the split block at the top of the block.
62571d5a254SDimitry Andric       // The predicate info for assumes will be somewhere in the middle,
62671d5a254SDimitry Andric       // it will get materialized in front of the assume.
62771d5a254SDimitry Andric       if (const auto *PAssume = dyn_cast<PredicateAssume>(PossibleCopy)) {
62871d5a254SDimitry Andric         VD.LocalNum = LN_Middle;
62971d5a254SDimitry Andric         DomTreeNode *DomNode = DT.getNode(PAssume->AssumeInst->getParent());
63071d5a254SDimitry Andric         if (!DomNode)
63171d5a254SDimitry Andric           continue;
63271d5a254SDimitry Andric         VD.DFSIn = DomNode->getDFSNumIn();
63371d5a254SDimitry Andric         VD.DFSOut = DomNode->getDFSNumOut();
63471d5a254SDimitry Andric         VD.PInfo = PossibleCopy;
63571d5a254SDimitry Andric         OrderedUses.push_back(VD);
63671d5a254SDimitry Andric       } else if (isa<PredicateWithEdge>(PossibleCopy)) {
63771d5a254SDimitry Andric         // If we can only do phi uses, we treat it like it's in the branch
63871d5a254SDimitry Andric         // block, and handle it specially. We know that it goes last, and only
63971d5a254SDimitry Andric         // dominate phi uses.
64071d5a254SDimitry Andric         auto BlockEdge = getBlockEdge(PossibleCopy);
64171d5a254SDimitry Andric         if (EdgeUsesOnly.count(BlockEdge)) {
64271d5a254SDimitry Andric           VD.LocalNum = LN_Last;
64371d5a254SDimitry Andric           auto *DomNode = DT.getNode(BlockEdge.first);
64471d5a254SDimitry Andric           if (DomNode) {
64571d5a254SDimitry Andric             VD.DFSIn = DomNode->getDFSNumIn();
64671d5a254SDimitry Andric             VD.DFSOut = DomNode->getDFSNumOut();
64771d5a254SDimitry Andric             VD.PInfo = PossibleCopy;
64871d5a254SDimitry Andric             VD.EdgeOnly = true;
64971d5a254SDimitry Andric             OrderedUses.push_back(VD);
65071d5a254SDimitry Andric           }
65171d5a254SDimitry Andric         } else {
65271d5a254SDimitry Andric           // Otherwise, we are in the split block (even though we perform
65371d5a254SDimitry Andric           // insertion in the branch block).
65471d5a254SDimitry Andric           // Insert a possible copy at the split block and before the branch.
65571d5a254SDimitry Andric           VD.LocalNum = LN_First;
65671d5a254SDimitry Andric           auto *DomNode = DT.getNode(BlockEdge.second);
65771d5a254SDimitry Andric           if (DomNode) {
65871d5a254SDimitry Andric             VD.DFSIn = DomNode->getDFSNumIn();
65971d5a254SDimitry Andric             VD.DFSOut = DomNode->getDFSNumOut();
66071d5a254SDimitry Andric             VD.PInfo = PossibleCopy;
66171d5a254SDimitry Andric             OrderedUses.push_back(VD);
66271d5a254SDimitry Andric           }
66371d5a254SDimitry Andric         }
66471d5a254SDimitry Andric       }
66571d5a254SDimitry Andric     }
66671d5a254SDimitry Andric 
66771d5a254SDimitry Andric     convertUsesToDFSOrdered(Op, OrderedUses);
668044eb2f6SDimitry Andric     // Here we require a stable sort because we do not bother to try to
669044eb2f6SDimitry Andric     // assign an order to the operands the uses represent. Thus, two
670044eb2f6SDimitry Andric     // uses in the same instruction do not have a strict sort order
671044eb2f6SDimitry Andric     // currently and will be considered equal. We could get rid of the
672044eb2f6SDimitry Andric     // stable sort by creating one if we wanted.
673e6d15924SDimitry Andric     llvm::stable_sort(OrderedUses, Compare);
67471d5a254SDimitry Andric     SmallVector<ValueDFS, 8> RenameStack;
67571d5a254SDimitry Andric     // For each use, sorted into dfs order, push values and replaces uses with
67671d5a254SDimitry Andric     // top of stack, which will represent the reaching def.
67771d5a254SDimitry Andric     for (auto &VD : OrderedUses) {
67871d5a254SDimitry Andric       // We currently do not materialize copy over copy, but we should decide if
67971d5a254SDimitry Andric       // we want to.
68071d5a254SDimitry Andric       bool PossibleCopy = VD.PInfo != nullptr;
68171d5a254SDimitry Andric       if (RenameStack.empty()) {
682eb11fae6SDimitry Andric         LLVM_DEBUG(dbgs() << "Rename Stack is empty\n");
68371d5a254SDimitry Andric       } else {
684eb11fae6SDimitry Andric         LLVM_DEBUG(dbgs() << "Rename Stack Top DFS numbers are ("
68571d5a254SDimitry Andric                           << RenameStack.back().DFSIn << ","
68671d5a254SDimitry Andric                           << RenameStack.back().DFSOut << ")\n");
68771d5a254SDimitry Andric       }
68871d5a254SDimitry Andric 
689eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "Current DFS numbers are (" << VD.DFSIn << ","
69071d5a254SDimitry Andric                         << VD.DFSOut << ")\n");
69171d5a254SDimitry Andric 
69271d5a254SDimitry Andric       bool ShouldPush = (VD.Def || PossibleCopy);
69371d5a254SDimitry Andric       bool OutOfScope = !stackIsInScope(RenameStack, VD);
69471d5a254SDimitry Andric       if (OutOfScope || ShouldPush) {
69571d5a254SDimitry Andric         // Sync to our current scope.
69671d5a254SDimitry Andric         popStackUntilDFSScope(RenameStack, VD);
69771d5a254SDimitry Andric         if (ShouldPush) {
69871d5a254SDimitry Andric           RenameStack.push_back(VD);
69971d5a254SDimitry Andric         }
70071d5a254SDimitry Andric       }
70171d5a254SDimitry Andric       // If we get to this point, and the stack is empty we must have a use
70271d5a254SDimitry Andric       // with no renaming needed, just skip it.
70371d5a254SDimitry Andric       if (RenameStack.empty())
70471d5a254SDimitry Andric         continue;
70571d5a254SDimitry Andric       // Skip values, only want to rename the uses
70671d5a254SDimitry Andric       if (VD.Def || PossibleCopy)
70771d5a254SDimitry Andric         continue;
70871d5a254SDimitry Andric       if (!DebugCounter::shouldExecute(RenameCounter)) {
709eb11fae6SDimitry Andric         LLVM_DEBUG(dbgs() << "Skipping execution due to debug counter\n");
71071d5a254SDimitry Andric         continue;
71171d5a254SDimitry Andric       }
71271d5a254SDimitry Andric       ValueDFS &Result = RenameStack.back();
71371d5a254SDimitry Andric 
71471d5a254SDimitry Andric       // If the possible copy dominates something, materialize our stack up to
71571d5a254SDimitry Andric       // this point. This ensures every comparison that affects our operation
71671d5a254SDimitry Andric       // ends up with predicateinfo.
71771d5a254SDimitry Andric       if (!Result.Def)
71871d5a254SDimitry Andric         Result.Def = materializeStack(Counter, RenameStack, Op);
71971d5a254SDimitry Andric 
720eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "Found replacement " << *Result.Def << " for "
721eb11fae6SDimitry Andric                         << *VD.U->get() << " in " << *(VD.U->getUser())
722eb11fae6SDimitry Andric                         << "\n");
72371d5a254SDimitry Andric       assert(DT.dominates(cast<Instruction>(Result.Def), *VD.U) &&
72471d5a254SDimitry Andric              "Predicateinfo def should have dominated this use");
72571d5a254SDimitry Andric       VD.U->set(Result.Def);
72671d5a254SDimitry Andric     }
72771d5a254SDimitry Andric   }
72871d5a254SDimitry Andric }
72971d5a254SDimitry Andric 
730cfca06d7SDimitry Andric PredicateInfoBuilder::ValueInfo &
getOrCreateValueInfo(Value * Operand)731cfca06d7SDimitry Andric PredicateInfoBuilder::getOrCreateValueInfo(Value *Operand) {
73271d5a254SDimitry Andric   auto OIN = ValueInfoNums.find(Operand);
73371d5a254SDimitry Andric   if (OIN == ValueInfoNums.end()) {
73471d5a254SDimitry Andric     // This will grow it
73571d5a254SDimitry Andric     ValueInfos.resize(ValueInfos.size() + 1);
73671d5a254SDimitry Andric     // This will use the new size and give us a 0 based number of the info
73771d5a254SDimitry Andric     auto InsertResult = ValueInfoNums.insert({Operand, ValueInfos.size() - 1});
73871d5a254SDimitry Andric     assert(InsertResult.second && "Value info number already existed?");
73971d5a254SDimitry Andric     return ValueInfos[InsertResult.first->second];
74071d5a254SDimitry Andric   }
74171d5a254SDimitry Andric   return ValueInfos[OIN->second];
74271d5a254SDimitry Andric }
74371d5a254SDimitry Andric 
744cfca06d7SDimitry Andric const PredicateInfoBuilder::ValueInfo &
getValueInfo(Value * Operand) const745cfca06d7SDimitry Andric PredicateInfoBuilder::getValueInfo(Value *Operand) const {
74671d5a254SDimitry Andric   auto OINI = ValueInfoNums.lookup(Operand);
74771d5a254SDimitry Andric   assert(OINI != 0 && "Operand was not really in the Value Info Numbers");
74871d5a254SDimitry Andric   assert(OINI < ValueInfos.size() &&
74971d5a254SDimitry Andric          "Value Info Number greater than size of Value Info Table");
75071d5a254SDimitry Andric   return ValueInfos[OINI];
75171d5a254SDimitry Andric }
75271d5a254SDimitry Andric 
PredicateInfo(Function & F,DominatorTree & DT,AssumptionCache & AC)75371d5a254SDimitry Andric PredicateInfo::PredicateInfo(Function &F, DominatorTree &DT,
75471d5a254SDimitry Andric                              AssumptionCache &AC)
755cfca06d7SDimitry Andric     : F(F) {
756cfca06d7SDimitry Andric   PredicateInfoBuilder Builder(*this, F, DT, AC);
757cfca06d7SDimitry Andric   Builder.buildPredicateInfo();
75871d5a254SDimitry Andric }
75971d5a254SDimitry Andric 
760c0981da4SDimitry Andric // Remove all declarations we created . The PredicateInfo consumers are
761c0981da4SDimitry Andric // responsible for remove the ssa_copy calls created.
~PredicateInfo()762c0981da4SDimitry Andric PredicateInfo::~PredicateInfo() {
763c0981da4SDimitry Andric   // Collect function pointers in set first, as SmallSet uses a SmallVector
764c0981da4SDimitry Andric   // internally and we have to remove the asserting value handles first.
765c0981da4SDimitry Andric   SmallPtrSet<Function *, 20> FunctionPtrs;
766e3b55780SDimitry Andric   for (const auto &F : CreatedDeclarations)
767c0981da4SDimitry Andric     FunctionPtrs.insert(&*F);
768c0981da4SDimitry Andric   CreatedDeclarations.clear();
769c0981da4SDimitry Andric 
770c0981da4SDimitry Andric   for (Function *F : FunctionPtrs) {
771c0981da4SDimitry Andric     assert(F->user_begin() == F->user_end() &&
772c0981da4SDimitry Andric            "PredicateInfo consumer did not remove all SSA copies.");
773c0981da4SDimitry Andric     F->eraseFromParent();
774c0981da4SDimitry Andric   }
775c0981da4SDimitry Andric }
776c0981da4SDimitry Andric 
getConstraint() const777e3b55780SDimitry Andric std::optional<PredicateConstraint> PredicateBase::getConstraint() const {
778b60736ecSDimitry Andric   switch (Type) {
779b60736ecSDimitry Andric   case PT_Assume:
780b60736ecSDimitry Andric   case PT_Branch: {
781b60736ecSDimitry Andric     bool TrueEdge = true;
782b60736ecSDimitry Andric     if (auto *PBranch = dyn_cast<PredicateBranch>(this))
783b60736ecSDimitry Andric       TrueEdge = PBranch->TrueEdge;
784b60736ecSDimitry Andric 
785b60736ecSDimitry Andric     if (Condition == RenamedOp) {
786b60736ecSDimitry Andric       return {{CmpInst::ICMP_EQ,
787b60736ecSDimitry Andric                TrueEdge ? ConstantInt::getTrue(Condition->getType())
788b60736ecSDimitry Andric                         : ConstantInt::getFalse(Condition->getType())}};
789b60736ecSDimitry Andric     }
790b60736ecSDimitry Andric 
791b60736ecSDimitry Andric     CmpInst *Cmp = dyn_cast<CmpInst>(Condition);
792b60736ecSDimitry Andric     if (!Cmp) {
793b60736ecSDimitry Andric       // TODO: Make this an assertion once RenamedOp is fully accurate.
794e3b55780SDimitry Andric       return std::nullopt;
795b60736ecSDimitry Andric     }
796b60736ecSDimitry Andric 
797b60736ecSDimitry Andric     CmpInst::Predicate Pred;
798b60736ecSDimitry Andric     Value *OtherOp;
799b60736ecSDimitry Andric     if (Cmp->getOperand(0) == RenamedOp) {
800b60736ecSDimitry Andric       Pred = Cmp->getPredicate();
801b60736ecSDimitry Andric       OtherOp = Cmp->getOperand(1);
802b60736ecSDimitry Andric     } else if (Cmp->getOperand(1) == RenamedOp) {
803b60736ecSDimitry Andric       Pred = Cmp->getSwappedPredicate();
804b60736ecSDimitry Andric       OtherOp = Cmp->getOperand(0);
805b60736ecSDimitry Andric     } else {
806b60736ecSDimitry Andric       // TODO: Make this an assertion once RenamedOp is fully accurate.
807e3b55780SDimitry Andric       return std::nullopt;
808b60736ecSDimitry Andric     }
809b60736ecSDimitry Andric 
810b60736ecSDimitry Andric     // Invert predicate along false edge.
811b60736ecSDimitry Andric     if (!TrueEdge)
812b60736ecSDimitry Andric       Pred = CmpInst::getInversePredicate(Pred);
813b60736ecSDimitry Andric 
814b60736ecSDimitry Andric     return {{Pred, OtherOp}};
815b60736ecSDimitry Andric   }
816b60736ecSDimitry Andric   case PT_Switch:
817b60736ecSDimitry Andric     if (Condition != RenamedOp) {
818b60736ecSDimitry Andric       // TODO: Make this an assertion once RenamedOp is fully accurate.
819e3b55780SDimitry Andric       return std::nullopt;
820b60736ecSDimitry Andric     }
821b60736ecSDimitry Andric 
822b60736ecSDimitry Andric     return {{CmpInst::ICMP_EQ, cast<PredicateSwitch>(this)->CaseValue}};
823b60736ecSDimitry Andric   }
824b60736ecSDimitry Andric   llvm_unreachable("Unknown predicate type");
825b60736ecSDimitry Andric }
826b60736ecSDimitry Andric 
verifyPredicateInfo() const82771d5a254SDimitry Andric void PredicateInfo::verifyPredicateInfo() const {}
82871d5a254SDimitry Andric 
829c0981da4SDimitry Andric // Replace ssa_copy calls created by PredicateInfo with their operand.
replaceCreatedSSACopys(PredicateInfo & PredInfo,Function & F)830c0981da4SDimitry Andric static void replaceCreatedSSACopys(PredicateInfo &PredInfo, Function &F) {
831c0981da4SDimitry Andric   for (Instruction &Inst : llvm::make_early_inc_range(instructions(F))) {
832c0981da4SDimitry Andric     const auto *PI = PredInfo.getPredicateInfoFor(&Inst);
833c0981da4SDimitry Andric     auto *II = dyn_cast<IntrinsicInst>(&Inst);
834c0981da4SDimitry Andric     if (!PI || !II || II->getIntrinsicID() != Intrinsic::ssa_copy)
835c0981da4SDimitry Andric       continue;
836c0981da4SDimitry Andric 
837c0981da4SDimitry Andric     Inst.replaceAllUsesWith(II->getOperand(0));
838c0981da4SDimitry Andric     Inst.eraseFromParent();
839c0981da4SDimitry Andric   }
840c0981da4SDimitry Andric }
841c0981da4SDimitry Andric 
run(Function & F,FunctionAnalysisManager & AM)84271d5a254SDimitry Andric PreservedAnalyses PredicateInfoPrinterPass::run(Function &F,
84371d5a254SDimitry Andric                                                 FunctionAnalysisManager &AM) {
84471d5a254SDimitry Andric   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
84571d5a254SDimitry Andric   auto &AC = AM.getResult<AssumptionAnalysis>(F);
84671d5a254SDimitry Andric   OS << "PredicateInfo for function: " << F.getName() << "\n";
8471d5ae102SDimitry Andric   auto PredInfo = std::make_unique<PredicateInfo>(F, DT, AC);
848eb11fae6SDimitry Andric   PredInfo->print(OS);
84971d5a254SDimitry Andric 
850c0981da4SDimitry Andric   replaceCreatedSSACopys(*PredInfo, F);
85171d5a254SDimitry Andric   return PreservedAnalyses::all();
85271d5a254SDimitry Andric }
85371d5a254SDimitry Andric 
854eb11fae6SDimitry Andric /// An assembly annotator class to print PredicateInfo information in
85571d5a254SDimitry Andric /// comments.
85671d5a254SDimitry Andric class PredicateInfoAnnotatedWriter : public AssemblyAnnotationWriter {
85771d5a254SDimitry Andric   friend class PredicateInfo;
85871d5a254SDimitry Andric   const PredicateInfo *PredInfo;
85971d5a254SDimitry Andric 
86071d5a254SDimitry Andric public:
PredicateInfoAnnotatedWriter(const PredicateInfo * M)86171d5a254SDimitry Andric   PredicateInfoAnnotatedWriter(const PredicateInfo *M) : PredInfo(M) {}
86271d5a254SDimitry Andric 
emitBasicBlockStartAnnot(const BasicBlock * BB,formatted_raw_ostream & OS)863cfca06d7SDimitry Andric   void emitBasicBlockStartAnnot(const BasicBlock *BB,
864cfca06d7SDimitry Andric                                 formatted_raw_ostream &OS) override {}
86571d5a254SDimitry Andric 
emitInstructionAnnot(const Instruction * I,formatted_raw_ostream & OS)866cfca06d7SDimitry Andric   void emitInstructionAnnot(const Instruction *I,
867cfca06d7SDimitry Andric                             formatted_raw_ostream &OS) override {
86871d5a254SDimitry Andric     if (const auto *PI = PredInfo->getPredicateInfoFor(I)) {
86971d5a254SDimitry Andric       OS << "; Has predicate info\n";
87071d5a254SDimitry Andric       if (const auto *PB = dyn_cast<PredicateBranch>(PI)) {
87171d5a254SDimitry Andric         OS << "; branch predicate info { TrueEdge: " << PB->TrueEdge
87271d5a254SDimitry Andric            << " Comparison:" << *PB->Condition << " Edge: [";
87371d5a254SDimitry Andric         PB->From->printAsOperand(OS);
87471d5a254SDimitry Andric         OS << ",";
87571d5a254SDimitry Andric         PB->To->printAsOperand(OS);
876cfca06d7SDimitry Andric         OS << "]";
87771d5a254SDimitry Andric       } else if (const auto *PS = dyn_cast<PredicateSwitch>(PI)) {
87871d5a254SDimitry Andric         OS << "; switch predicate info { CaseValue: " << *PS->CaseValue
87971d5a254SDimitry Andric            << " Switch:" << *PS->Switch << " Edge: [";
88071d5a254SDimitry Andric         PS->From->printAsOperand(OS);
88171d5a254SDimitry Andric         OS << ",";
88271d5a254SDimitry Andric         PS->To->printAsOperand(OS);
883cfca06d7SDimitry Andric         OS << "]";
88471d5a254SDimitry Andric       } else if (const auto *PA = dyn_cast<PredicateAssume>(PI)) {
88571d5a254SDimitry Andric         OS << "; assume predicate info {"
886cfca06d7SDimitry Andric            << " Comparison:" << *PA->Condition;
88771d5a254SDimitry Andric       }
888cfca06d7SDimitry Andric       OS << ", RenamedOp: ";
889cfca06d7SDimitry Andric       PI->RenamedOp->printAsOperand(OS, false);
890cfca06d7SDimitry Andric       OS << " }\n";
89171d5a254SDimitry Andric     }
89271d5a254SDimitry Andric   }
89371d5a254SDimitry Andric };
89471d5a254SDimitry Andric 
print(raw_ostream & OS) const89571d5a254SDimitry Andric void PredicateInfo::print(raw_ostream &OS) const {
89671d5a254SDimitry Andric   PredicateInfoAnnotatedWriter Writer(this);
89771d5a254SDimitry Andric   F.print(OS, &Writer);
89871d5a254SDimitry Andric }
89971d5a254SDimitry Andric 
dump() const90071d5a254SDimitry Andric void PredicateInfo::dump() const {
90171d5a254SDimitry Andric   PredicateInfoAnnotatedWriter Writer(this);
90271d5a254SDimitry Andric   F.print(dbgs(), &Writer);
90371d5a254SDimitry Andric }
90471d5a254SDimitry Andric 
run(Function & F,FunctionAnalysisManager & AM)90571d5a254SDimitry Andric PreservedAnalyses PredicateInfoVerifierPass::run(Function &F,
90671d5a254SDimitry Andric                                                  FunctionAnalysisManager &AM) {
90771d5a254SDimitry Andric   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
90871d5a254SDimitry Andric   auto &AC = AM.getResult<AssumptionAnalysis>(F);
9091d5ae102SDimitry Andric   std::make_unique<PredicateInfo>(F, DT, AC)->verifyPredicateInfo();
91071d5a254SDimitry Andric 
91171d5a254SDimitry Andric   return PreservedAnalyses::all();
91271d5a254SDimitry Andric }
91371d5a254SDimitry Andric }
914