xref: /openbsd-src/gnu/llvm/llvm/lib/Transforms/Utils/PredicateInfo.cpp (revision 73471bf04ceb096474c7f0fa83b1b65c70a787a1)
109467b48Spatrick //===-- PredicateInfo.cpp - PredicateInfo Builder--------------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This file implements the PredicateInfo class.
1009467b48Spatrick //
1109467b48Spatrick //===----------------------------------------------------------------===//
1209467b48Spatrick 
1309467b48Spatrick #include "llvm/Transforms/Utils/PredicateInfo.h"
1409467b48Spatrick #include "llvm/ADT/DenseMap.h"
1509467b48Spatrick #include "llvm/ADT/DepthFirstIterator.h"
1609467b48Spatrick #include "llvm/ADT/STLExtras.h"
1709467b48Spatrick #include "llvm/ADT/SmallPtrSet.h"
1809467b48Spatrick #include "llvm/ADT/Statistic.h"
1909467b48Spatrick #include "llvm/ADT/StringExtras.h"
2009467b48Spatrick #include "llvm/Analysis/AssumptionCache.h"
2109467b48Spatrick #include "llvm/Analysis/CFG.h"
2209467b48Spatrick #include "llvm/IR/AssemblyAnnotationWriter.h"
2309467b48Spatrick #include "llvm/IR/DataLayout.h"
2409467b48Spatrick #include "llvm/IR/Dominators.h"
2509467b48Spatrick #include "llvm/IR/GlobalVariable.h"
2609467b48Spatrick #include "llvm/IR/IRBuilder.h"
2709467b48Spatrick #include "llvm/IR/InstIterator.h"
2809467b48Spatrick #include "llvm/IR/IntrinsicInst.h"
2909467b48Spatrick #include "llvm/IR/LLVMContext.h"
3009467b48Spatrick #include "llvm/IR/Metadata.h"
3109467b48Spatrick #include "llvm/IR/Module.h"
3209467b48Spatrick #include "llvm/IR/PatternMatch.h"
3309467b48Spatrick #include "llvm/InitializePasses.h"
34097a140dSpatrick #include "llvm/Support/CommandLine.h"
3509467b48Spatrick #include "llvm/Support/Debug.h"
3609467b48Spatrick #include "llvm/Support/DebugCounter.h"
3709467b48Spatrick #include "llvm/Support/FormattedStream.h"
3809467b48Spatrick #include "llvm/Transforms/Utils.h"
3909467b48Spatrick #include <algorithm>
4009467b48Spatrick #define DEBUG_TYPE "predicateinfo"
4109467b48Spatrick using namespace llvm;
4209467b48Spatrick using namespace PatternMatch;
4309467b48Spatrick 
4409467b48Spatrick INITIALIZE_PASS_BEGIN(PredicateInfoPrinterLegacyPass, "print-predicateinfo",
4509467b48Spatrick                       "PredicateInfo Printer", false, false)
4609467b48Spatrick INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4709467b48Spatrick INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
4809467b48Spatrick INITIALIZE_PASS_END(PredicateInfoPrinterLegacyPass, "print-predicateinfo",
4909467b48Spatrick                     "PredicateInfo Printer", false, false)
5009467b48Spatrick static cl::opt<bool> VerifyPredicateInfo(
5109467b48Spatrick     "verify-predicateinfo", cl::init(false), cl::Hidden,
5209467b48Spatrick     cl::desc("Verify PredicateInfo in legacy printer pass."));
5309467b48Spatrick DEBUG_COUNTER(RenameCounter, "predicateinfo-rename",
5409467b48Spatrick               "Controls which variables are renamed with predicateinfo");
5509467b48Spatrick 
56*73471bf0Spatrick // Maximum number of conditions considered for renaming for each branch/assume.
57*73471bf0Spatrick // This limits renaming of deep and/or chains.
58*73471bf0Spatrick static const unsigned MaxCondsPerBranch = 8;
59*73471bf0Spatrick 
6009467b48Spatrick namespace {
6109467b48Spatrick // Given a predicate info that is a type of branching terminator, get the
6209467b48Spatrick // branching block.
6309467b48Spatrick const BasicBlock *getBranchBlock(const PredicateBase *PB) {
6409467b48Spatrick   assert(isa<PredicateWithEdge>(PB) &&
6509467b48Spatrick          "Only branches and switches should have PHIOnly defs that "
6609467b48Spatrick          "require branch blocks.");
6709467b48Spatrick   return cast<PredicateWithEdge>(PB)->From;
6809467b48Spatrick }
6909467b48Spatrick 
7009467b48Spatrick // Given a predicate info that is a type of branching terminator, get the
7109467b48Spatrick // branching terminator.
7209467b48Spatrick static Instruction *getBranchTerminator(const PredicateBase *PB) {
7309467b48Spatrick   assert(isa<PredicateWithEdge>(PB) &&
7409467b48Spatrick          "Not a predicate info type we know how to get a terminator from.");
7509467b48Spatrick   return cast<PredicateWithEdge>(PB)->From->getTerminator();
7609467b48Spatrick }
7709467b48Spatrick 
7809467b48Spatrick // Given a predicate info that is a type of branching terminator, get the
7909467b48Spatrick // edge this predicate info represents
80*73471bf0Spatrick std::pair<BasicBlock *, BasicBlock *> getBlockEdge(const PredicateBase *PB) {
8109467b48Spatrick   assert(isa<PredicateWithEdge>(PB) &&
8209467b48Spatrick          "Not a predicate info type we know how to get an edge from.");
8309467b48Spatrick   const auto *PEdge = cast<PredicateWithEdge>(PB);
8409467b48Spatrick   return std::make_pair(PEdge->From, PEdge->To);
8509467b48Spatrick }
8609467b48Spatrick }
8709467b48Spatrick 
8809467b48Spatrick namespace llvm {
8909467b48Spatrick enum LocalNum {
9009467b48Spatrick   // Operations that must appear first in the block.
9109467b48Spatrick   LN_First,
9209467b48Spatrick   // Operations that are somewhere in the middle of the block, and are sorted on
9309467b48Spatrick   // demand.
9409467b48Spatrick   LN_Middle,
9509467b48Spatrick   // Operations that must appear last in a block, like successor phi node uses.
9609467b48Spatrick   LN_Last
9709467b48Spatrick };
9809467b48Spatrick 
9909467b48Spatrick // Associate global and local DFS info with defs and uses, so we can sort them
10009467b48Spatrick // into a global domination ordering.
10109467b48Spatrick struct ValueDFS {
10209467b48Spatrick   int DFSIn = 0;
10309467b48Spatrick   int DFSOut = 0;
10409467b48Spatrick   unsigned int LocalNum = LN_Middle;
10509467b48Spatrick   // Only one of Def or Use will be set.
10609467b48Spatrick   Value *Def = nullptr;
10709467b48Spatrick   Use *U = nullptr;
10809467b48Spatrick   // Neither PInfo nor EdgeOnly participate in the ordering
10909467b48Spatrick   PredicateBase *PInfo = nullptr;
11009467b48Spatrick   bool EdgeOnly = false;
11109467b48Spatrick };
11209467b48Spatrick 
11309467b48Spatrick // Perform a strict weak ordering on instructions and arguments.
114097a140dSpatrick static bool valueComesBefore(const Value *A, const Value *B) {
11509467b48Spatrick   auto *ArgA = dyn_cast_or_null<Argument>(A);
11609467b48Spatrick   auto *ArgB = dyn_cast_or_null<Argument>(B);
11709467b48Spatrick   if (ArgA && !ArgB)
11809467b48Spatrick     return true;
11909467b48Spatrick   if (ArgB && !ArgA)
12009467b48Spatrick     return false;
12109467b48Spatrick   if (ArgA && ArgB)
12209467b48Spatrick     return ArgA->getArgNo() < ArgB->getArgNo();
123097a140dSpatrick   return cast<Instruction>(A)->comesBefore(cast<Instruction>(B));
12409467b48Spatrick }
12509467b48Spatrick 
126097a140dSpatrick // This compares ValueDFS structures. Doing so allows us to walk the minimum
127097a140dSpatrick // number of instructions necessary to compute our def/use ordering.
12809467b48Spatrick struct ValueDFS_Compare {
12909467b48Spatrick   DominatorTree &DT;
130097a140dSpatrick   ValueDFS_Compare(DominatorTree &DT) : DT(DT) {}
13109467b48Spatrick 
13209467b48Spatrick   bool operator()(const ValueDFS &A, const ValueDFS &B) const {
13309467b48Spatrick     if (&A == &B)
13409467b48Spatrick       return false;
13509467b48Spatrick     // The only case we can't directly compare them is when they in the same
13609467b48Spatrick     // block, and both have localnum == middle.  In that case, we have to use
13709467b48Spatrick     // comesbefore to see what the real ordering is, because they are in the
13809467b48Spatrick     // same basic block.
13909467b48Spatrick 
14009467b48Spatrick     assert((A.DFSIn != B.DFSIn || A.DFSOut == B.DFSOut) &&
14109467b48Spatrick            "Equal DFS-in numbers imply equal out numbers");
14209467b48Spatrick     bool SameBlock = A.DFSIn == B.DFSIn;
14309467b48Spatrick 
14409467b48Spatrick     // We want to put the def that will get used for a given set of phi uses,
14509467b48Spatrick     // before those phi uses.
14609467b48Spatrick     // So we sort by edge, then by def.
14709467b48Spatrick     // Note that only phi nodes uses and defs can come last.
14809467b48Spatrick     if (SameBlock && A.LocalNum == LN_Last && B.LocalNum == LN_Last)
14909467b48Spatrick       return comparePHIRelated(A, B);
15009467b48Spatrick 
15109467b48Spatrick     bool isADef = A.Def;
15209467b48Spatrick     bool isBDef = B.Def;
15309467b48Spatrick     if (!SameBlock || A.LocalNum != LN_Middle || B.LocalNum != LN_Middle)
15409467b48Spatrick       return std::tie(A.DFSIn, A.LocalNum, isADef) <
15509467b48Spatrick              std::tie(B.DFSIn, B.LocalNum, isBDef);
15609467b48Spatrick     return localComesBefore(A, B);
15709467b48Spatrick   }
15809467b48Spatrick 
15909467b48Spatrick   // For a phi use, or a non-materialized def, return the edge it represents.
160*73471bf0Spatrick   std::pair<BasicBlock *, BasicBlock *> getBlockEdge(const ValueDFS &VD) const {
16109467b48Spatrick     if (!VD.Def && VD.U) {
16209467b48Spatrick       auto *PHI = cast<PHINode>(VD.U->getUser());
16309467b48Spatrick       return std::make_pair(PHI->getIncomingBlock(*VD.U), PHI->getParent());
16409467b48Spatrick     }
16509467b48Spatrick     // This is really a non-materialized def.
16609467b48Spatrick     return ::getBlockEdge(VD.PInfo);
16709467b48Spatrick   }
16809467b48Spatrick 
16909467b48Spatrick   // For two phi related values, return the ordering.
17009467b48Spatrick   bool comparePHIRelated(const ValueDFS &A, const ValueDFS &B) const {
17109467b48Spatrick     BasicBlock *ASrc, *ADest, *BSrc, *BDest;
17209467b48Spatrick     std::tie(ASrc, ADest) = getBlockEdge(A);
17309467b48Spatrick     std::tie(BSrc, BDest) = getBlockEdge(B);
17409467b48Spatrick 
17509467b48Spatrick #ifndef NDEBUG
17609467b48Spatrick     // This function should only be used for values in the same BB, check that.
17709467b48Spatrick     DomTreeNode *DomASrc = DT.getNode(ASrc);
17809467b48Spatrick     DomTreeNode *DomBSrc = DT.getNode(BSrc);
17909467b48Spatrick     assert(DomASrc->getDFSNumIn() == (unsigned)A.DFSIn &&
18009467b48Spatrick            "DFS numbers for A should match the ones of the source block");
18109467b48Spatrick     assert(DomBSrc->getDFSNumIn() == (unsigned)B.DFSIn &&
18209467b48Spatrick            "DFS numbers for B should match the ones of the source block");
18309467b48Spatrick     assert(A.DFSIn == B.DFSIn && "Values must be in the same block");
18409467b48Spatrick #endif
18509467b48Spatrick     (void)ASrc;
18609467b48Spatrick     (void)BSrc;
18709467b48Spatrick 
18809467b48Spatrick     // Use DFS numbers to compare destination blocks, to guarantee a
18909467b48Spatrick     // deterministic order.
19009467b48Spatrick     DomTreeNode *DomADest = DT.getNode(ADest);
19109467b48Spatrick     DomTreeNode *DomBDest = DT.getNode(BDest);
19209467b48Spatrick     unsigned AIn = DomADest->getDFSNumIn();
19309467b48Spatrick     unsigned BIn = DomBDest->getDFSNumIn();
19409467b48Spatrick     bool isADef = A.Def;
19509467b48Spatrick     bool isBDef = B.Def;
19609467b48Spatrick     assert((!A.Def || !A.U) && (!B.Def || !B.U) &&
19709467b48Spatrick            "Def and U cannot be set at the same time");
19809467b48Spatrick     // Now sort by edge destination and then defs before uses.
19909467b48Spatrick     return std::tie(AIn, isADef) < std::tie(BIn, isBDef);
20009467b48Spatrick   }
20109467b48Spatrick 
20209467b48Spatrick   // Get the definition of an instruction that occurs in the middle of a block.
20309467b48Spatrick   Value *getMiddleDef(const ValueDFS &VD) const {
20409467b48Spatrick     if (VD.Def)
20509467b48Spatrick       return VD.Def;
20609467b48Spatrick     // It's possible for the defs and uses to be null.  For branches, the local
20709467b48Spatrick     // numbering will say the placed predicaeinfos should go first (IE
20809467b48Spatrick     // LN_beginning), so we won't be in this function. For assumes, we will end
20909467b48Spatrick     // up here, beause we need to order the def we will place relative to the
210097a140dSpatrick     // assume.  So for the purpose of ordering, we pretend the def is right
211097a140dSpatrick     // after the assume, because that is where we will insert the info.
21209467b48Spatrick     if (!VD.U) {
21309467b48Spatrick       assert(VD.PInfo &&
21409467b48Spatrick              "No def, no use, and no predicateinfo should not occur");
21509467b48Spatrick       assert(isa<PredicateAssume>(VD.PInfo) &&
21609467b48Spatrick              "Middle of block should only occur for assumes");
217097a140dSpatrick       return cast<PredicateAssume>(VD.PInfo)->AssumeInst->getNextNode();
21809467b48Spatrick     }
21909467b48Spatrick     return nullptr;
22009467b48Spatrick   }
22109467b48Spatrick 
22209467b48Spatrick   // Return either the Def, if it's not null, or the user of the Use, if the def
22309467b48Spatrick   // is null.
22409467b48Spatrick   const Instruction *getDefOrUser(const Value *Def, const Use *U) const {
22509467b48Spatrick     if (Def)
22609467b48Spatrick       return cast<Instruction>(Def);
22709467b48Spatrick     return cast<Instruction>(U->getUser());
22809467b48Spatrick   }
22909467b48Spatrick 
23009467b48Spatrick   // This performs the necessary local basic block ordering checks to tell
23109467b48Spatrick   // whether A comes before B, where both are in the same basic block.
23209467b48Spatrick   bool localComesBefore(const ValueDFS &A, const ValueDFS &B) const {
23309467b48Spatrick     auto *ADef = getMiddleDef(A);
23409467b48Spatrick     auto *BDef = getMiddleDef(B);
23509467b48Spatrick 
23609467b48Spatrick     // See if we have real values or uses. If we have real values, we are
23709467b48Spatrick     // guaranteed they are instructions or arguments. No matter what, we are
23809467b48Spatrick     // guaranteed they are in the same block if they are instructions.
23909467b48Spatrick     auto *ArgA = dyn_cast_or_null<Argument>(ADef);
24009467b48Spatrick     auto *ArgB = dyn_cast_or_null<Argument>(BDef);
24109467b48Spatrick 
24209467b48Spatrick     if (ArgA || ArgB)
243097a140dSpatrick       return valueComesBefore(ArgA, ArgB);
24409467b48Spatrick 
24509467b48Spatrick     auto *AInst = getDefOrUser(ADef, A.U);
24609467b48Spatrick     auto *BInst = getDefOrUser(BDef, B.U);
247097a140dSpatrick     return valueComesBefore(AInst, BInst);
24809467b48Spatrick   }
24909467b48Spatrick };
25009467b48Spatrick 
251097a140dSpatrick class PredicateInfoBuilder {
252097a140dSpatrick   // Used to store information about each value we might rename.
253097a140dSpatrick   struct ValueInfo {
254097a140dSpatrick     SmallVector<PredicateBase *, 4> Infos;
255097a140dSpatrick   };
25609467b48Spatrick 
257097a140dSpatrick   PredicateInfo &PI;
258097a140dSpatrick   Function &F;
259097a140dSpatrick   DominatorTree &DT;
260097a140dSpatrick   AssumptionCache &AC;
261097a140dSpatrick 
262097a140dSpatrick   // This stores info about each operand or comparison result we make copies
263097a140dSpatrick   // of. The real ValueInfos start at index 1, index 0 is unused so that we
264097a140dSpatrick   // can more easily detect invalid indexing.
265097a140dSpatrick   SmallVector<ValueInfo, 32> ValueInfos;
266097a140dSpatrick 
267097a140dSpatrick   // This gives the index into the ValueInfos array for a given Value. Because
268097a140dSpatrick   // 0 is not a valid Value Info index, you can use DenseMap::lookup and tell
269097a140dSpatrick   // whether it returned a valid result.
270097a140dSpatrick   DenseMap<Value *, unsigned int> ValueInfoNums;
271097a140dSpatrick 
272097a140dSpatrick   // The set of edges along which we can only handle phi uses, due to critical
273097a140dSpatrick   // edges.
274097a140dSpatrick   DenseSet<std::pair<BasicBlock *, BasicBlock *>> EdgeUsesOnly;
275097a140dSpatrick 
276097a140dSpatrick   ValueInfo &getOrCreateValueInfo(Value *);
277097a140dSpatrick   const ValueInfo &getValueInfo(Value *) const;
278097a140dSpatrick 
279097a140dSpatrick   void processAssume(IntrinsicInst *, BasicBlock *,
280097a140dSpatrick                      SmallVectorImpl<Value *> &OpsToRename);
281097a140dSpatrick   void processBranch(BranchInst *, BasicBlock *,
282097a140dSpatrick                      SmallVectorImpl<Value *> &OpsToRename);
283097a140dSpatrick   void processSwitch(SwitchInst *, BasicBlock *,
284097a140dSpatrick                      SmallVectorImpl<Value *> &OpsToRename);
285097a140dSpatrick   void renameUses(SmallVectorImpl<Value *> &OpsToRename);
286097a140dSpatrick   void addInfoFor(SmallVectorImpl<Value *> &OpsToRename, Value *Op,
287097a140dSpatrick                   PredicateBase *PB);
288097a140dSpatrick 
289097a140dSpatrick   typedef SmallVectorImpl<ValueDFS> ValueDFSStack;
290097a140dSpatrick   void convertUsesToDFSOrdered(Value *, SmallVectorImpl<ValueDFS> &);
291097a140dSpatrick   Value *materializeStack(unsigned int &, ValueDFSStack &, Value *);
292097a140dSpatrick   bool stackIsInScope(const ValueDFSStack &, const ValueDFS &) const;
293097a140dSpatrick   void popStackUntilDFSScope(ValueDFSStack &, const ValueDFS &);
294097a140dSpatrick 
295097a140dSpatrick public:
296097a140dSpatrick   PredicateInfoBuilder(PredicateInfo &PI, Function &F, DominatorTree &DT,
297097a140dSpatrick                        AssumptionCache &AC)
298097a140dSpatrick       : PI(PI), F(F), DT(DT), AC(AC) {
299097a140dSpatrick     // Push an empty operand info so that we can detect 0 as not finding one
300097a140dSpatrick     ValueInfos.resize(1);
301097a140dSpatrick   }
302097a140dSpatrick 
303097a140dSpatrick   void buildPredicateInfo();
304097a140dSpatrick };
305097a140dSpatrick 
306097a140dSpatrick bool PredicateInfoBuilder::stackIsInScope(const ValueDFSStack &Stack,
30709467b48Spatrick                                           const ValueDFS &VDUse) const {
30809467b48Spatrick   if (Stack.empty())
30909467b48Spatrick     return false;
31009467b48Spatrick   // If it's a phi only use, make sure it's for this phi node edge, and that the
31109467b48Spatrick   // use is in a phi node.  If it's anything else, and the top of the stack is
31209467b48Spatrick   // EdgeOnly, we need to pop the stack.  We deliberately sort phi uses next to
31309467b48Spatrick   // the defs they must go with so that we can know it's time to pop the stack
31409467b48Spatrick   // when we hit the end of the phi uses for a given def.
31509467b48Spatrick   if (Stack.back().EdgeOnly) {
31609467b48Spatrick     if (!VDUse.U)
31709467b48Spatrick       return false;
31809467b48Spatrick     auto *PHI = dyn_cast<PHINode>(VDUse.U->getUser());
31909467b48Spatrick     if (!PHI)
32009467b48Spatrick       return false;
32109467b48Spatrick     // Check edge
32209467b48Spatrick     BasicBlock *EdgePred = PHI->getIncomingBlock(*VDUse.U);
32309467b48Spatrick     if (EdgePred != getBranchBlock(Stack.back().PInfo))
32409467b48Spatrick       return false;
32509467b48Spatrick 
32609467b48Spatrick     // Use dominates, which knows how to handle edge dominance.
32709467b48Spatrick     return DT.dominates(getBlockEdge(Stack.back().PInfo), *VDUse.U);
32809467b48Spatrick   }
32909467b48Spatrick 
33009467b48Spatrick   return (VDUse.DFSIn >= Stack.back().DFSIn &&
33109467b48Spatrick           VDUse.DFSOut <= Stack.back().DFSOut);
33209467b48Spatrick }
33309467b48Spatrick 
334097a140dSpatrick void PredicateInfoBuilder::popStackUntilDFSScope(ValueDFSStack &Stack,
33509467b48Spatrick                                                  const ValueDFS &VD) {
33609467b48Spatrick   while (!Stack.empty() && !stackIsInScope(Stack, VD))
33709467b48Spatrick     Stack.pop_back();
33809467b48Spatrick }
33909467b48Spatrick 
34009467b48Spatrick // Convert the uses of Op into a vector of uses, associating global and local
34109467b48Spatrick // DFS info with each one.
342097a140dSpatrick void PredicateInfoBuilder::convertUsesToDFSOrdered(
34309467b48Spatrick     Value *Op, SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
34409467b48Spatrick   for (auto &U : Op->uses()) {
34509467b48Spatrick     if (auto *I = dyn_cast<Instruction>(U.getUser())) {
34609467b48Spatrick       ValueDFS VD;
34709467b48Spatrick       // Put the phi node uses in the incoming block.
34809467b48Spatrick       BasicBlock *IBlock;
34909467b48Spatrick       if (auto *PN = dyn_cast<PHINode>(I)) {
35009467b48Spatrick         IBlock = PN->getIncomingBlock(U);
35109467b48Spatrick         // Make phi node users appear last in the incoming block
35209467b48Spatrick         // they are from.
35309467b48Spatrick         VD.LocalNum = LN_Last;
35409467b48Spatrick       } else {
35509467b48Spatrick         // If it's not a phi node use, it is somewhere in the middle of the
35609467b48Spatrick         // block.
35709467b48Spatrick         IBlock = I->getParent();
35809467b48Spatrick         VD.LocalNum = LN_Middle;
35909467b48Spatrick       }
36009467b48Spatrick       DomTreeNode *DomNode = DT.getNode(IBlock);
36109467b48Spatrick       // It's possible our use is in an unreachable block. Skip it if so.
36209467b48Spatrick       if (!DomNode)
36309467b48Spatrick         continue;
36409467b48Spatrick       VD.DFSIn = DomNode->getDFSNumIn();
36509467b48Spatrick       VD.DFSOut = DomNode->getDFSNumOut();
36609467b48Spatrick       VD.U = &U;
36709467b48Spatrick       DFSOrderedSet.push_back(VD);
36809467b48Spatrick     }
36909467b48Spatrick   }
37009467b48Spatrick }
37109467b48Spatrick 
372*73471bf0Spatrick bool shouldRename(Value *V) {
373*73471bf0Spatrick   // Only want real values, not constants.  Additionally, operands with one use
374*73471bf0Spatrick   // are only being used in the comparison, which means they will not be useful
375*73471bf0Spatrick   // for us to consider for predicateinfo.
376*73471bf0Spatrick   return (isa<Instruction>(V) || isa<Argument>(V)) && !V->hasOneUse();
377*73471bf0Spatrick }
378*73471bf0Spatrick 
37909467b48Spatrick // Collect relevant operations from Comparison that we may want to insert copies
38009467b48Spatrick // for.
38109467b48Spatrick void collectCmpOps(CmpInst *Comparison, SmallVectorImpl<Value *> &CmpOperands) {
38209467b48Spatrick   auto *Op0 = Comparison->getOperand(0);
38309467b48Spatrick   auto *Op1 = Comparison->getOperand(1);
38409467b48Spatrick   if (Op0 == Op1)
38509467b48Spatrick     return;
386*73471bf0Spatrick 
38709467b48Spatrick   CmpOperands.push_back(Op0);
38809467b48Spatrick   CmpOperands.push_back(Op1);
38909467b48Spatrick }
39009467b48Spatrick 
39109467b48Spatrick // Add Op, PB to the list of value infos for Op, and mark Op to be renamed.
392097a140dSpatrick void PredicateInfoBuilder::addInfoFor(SmallVectorImpl<Value *> &OpsToRename,
393097a140dSpatrick                                       Value *Op, PredicateBase *PB) {
39409467b48Spatrick   auto &OperandInfo = getOrCreateValueInfo(Op);
39509467b48Spatrick   if (OperandInfo.Infos.empty())
39609467b48Spatrick     OpsToRename.push_back(Op);
397097a140dSpatrick   PI.AllInfos.push_back(PB);
39809467b48Spatrick   OperandInfo.Infos.push_back(PB);
39909467b48Spatrick }
40009467b48Spatrick 
40109467b48Spatrick // Process an assume instruction and place relevant operations we want to rename
40209467b48Spatrick // into OpsToRename.
403097a140dSpatrick void PredicateInfoBuilder::processAssume(
404097a140dSpatrick     IntrinsicInst *II, BasicBlock *AssumeBB,
40509467b48Spatrick     SmallVectorImpl<Value *> &OpsToRename) {
406*73471bf0Spatrick   SmallVector<Value *, 4> Worklist;
407*73471bf0Spatrick   SmallPtrSet<Value *, 4> Visited;
408*73471bf0Spatrick   Worklist.push_back(II->getOperand(0));
409*73471bf0Spatrick   while (!Worklist.empty()) {
410*73471bf0Spatrick     Value *Cond = Worklist.pop_back_val();
411*73471bf0Spatrick     if (!Visited.insert(Cond).second)
412*73471bf0Spatrick       continue;
413*73471bf0Spatrick     if (Visited.size() > MaxCondsPerBranch)
414*73471bf0Spatrick       break;
41509467b48Spatrick 
416*73471bf0Spatrick     Value *Op0, *Op1;
417*73471bf0Spatrick     if (match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
418*73471bf0Spatrick       Worklist.push_back(Op1);
419*73471bf0Spatrick       Worklist.push_back(Op0);
42009467b48Spatrick     }
421*73471bf0Spatrick 
422*73471bf0Spatrick     SmallVector<Value *, 4> Values;
423*73471bf0Spatrick     Values.push_back(Cond);
424*73471bf0Spatrick     if (auto *Cmp = dyn_cast<CmpInst>(Cond))
425*73471bf0Spatrick       collectCmpOps(Cmp, Values);
426*73471bf0Spatrick 
427*73471bf0Spatrick     for (Value *V : Values) {
428*73471bf0Spatrick       if (shouldRename(V)) {
429*73471bf0Spatrick         auto *PA = new PredicateAssume(V, II, Cond);
430*73471bf0Spatrick         addInfoFor(OpsToRename, V, PA);
43109467b48Spatrick       }
43209467b48Spatrick     }
43309467b48Spatrick   }
43409467b48Spatrick }
43509467b48Spatrick 
43609467b48Spatrick // Process a block terminating branch, and place relevant operations to be
43709467b48Spatrick // renamed into OpsToRename.
438097a140dSpatrick void PredicateInfoBuilder::processBranch(
439097a140dSpatrick     BranchInst *BI, BasicBlock *BranchBB,
44009467b48Spatrick     SmallVectorImpl<Value *> &OpsToRename) {
44109467b48Spatrick   BasicBlock *FirstBB = BI->getSuccessor(0);
44209467b48Spatrick   BasicBlock *SecondBB = BI->getSuccessor(1);
44309467b48Spatrick 
444*73471bf0Spatrick   for (BasicBlock *Succ : {FirstBB, SecondBB}) {
445*73471bf0Spatrick     bool TakenEdge = Succ == FirstBB;
44609467b48Spatrick     // Don't try to insert on a self-edge. This is mainly because we will
44709467b48Spatrick     // eliminate during renaming anyway.
44809467b48Spatrick     if (Succ == BranchBB)
44909467b48Spatrick       continue;
450*73471bf0Spatrick 
451*73471bf0Spatrick     SmallVector<Value *, 4> Worklist;
452*73471bf0Spatrick     SmallPtrSet<Value *, 4> Visited;
453*73471bf0Spatrick     Worklist.push_back(BI->getCondition());
454*73471bf0Spatrick     while (!Worklist.empty()) {
455*73471bf0Spatrick       Value *Cond = Worklist.pop_back_val();
456*73471bf0Spatrick       if (!Visited.insert(Cond).second)
45709467b48Spatrick         continue;
458*73471bf0Spatrick       if (Visited.size() > MaxCondsPerBranch)
459*73471bf0Spatrick         break;
460*73471bf0Spatrick 
461*73471bf0Spatrick       Value *Op0, *Op1;
462*73471bf0Spatrick       if (TakenEdge ? match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))
463*73471bf0Spatrick                     : match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
464*73471bf0Spatrick         Worklist.push_back(Op1);
465*73471bf0Spatrick         Worklist.push_back(Op0);
466*73471bf0Spatrick       }
467*73471bf0Spatrick 
468*73471bf0Spatrick       SmallVector<Value *, 4> Values;
469*73471bf0Spatrick       Values.push_back(Cond);
470*73471bf0Spatrick       if (auto *Cmp = dyn_cast<CmpInst>(Cond))
471*73471bf0Spatrick         collectCmpOps(Cmp, Values);
472*73471bf0Spatrick 
473*73471bf0Spatrick       for (Value *V : Values) {
474*73471bf0Spatrick         if (shouldRename(V)) {
47509467b48Spatrick           PredicateBase *PB =
476*73471bf0Spatrick               new PredicateBranch(V, BranchBB, Succ, Cond, TakenEdge);
477*73471bf0Spatrick           addInfoFor(OpsToRename, V, PB);
47809467b48Spatrick           if (!Succ->getSinglePredecessor())
47909467b48Spatrick             EdgeUsesOnly.insert({BranchBB, Succ});
48009467b48Spatrick         }
48109467b48Spatrick       }
48209467b48Spatrick     }
48309467b48Spatrick   }
48409467b48Spatrick }
48509467b48Spatrick // Process a block terminating switch, and place relevant operations to be
48609467b48Spatrick // renamed into OpsToRename.
487097a140dSpatrick void PredicateInfoBuilder::processSwitch(
488097a140dSpatrick     SwitchInst *SI, BasicBlock *BranchBB,
48909467b48Spatrick     SmallVectorImpl<Value *> &OpsToRename) {
49009467b48Spatrick   Value *Op = SI->getCondition();
49109467b48Spatrick   if ((!isa<Instruction>(Op) && !isa<Argument>(Op)) || Op->hasOneUse())
49209467b48Spatrick     return;
49309467b48Spatrick 
49409467b48Spatrick   // Remember how many outgoing edges there are to every successor.
49509467b48Spatrick   SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
49609467b48Spatrick   for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
49709467b48Spatrick     BasicBlock *TargetBlock = SI->getSuccessor(i);
49809467b48Spatrick     ++SwitchEdges[TargetBlock];
49909467b48Spatrick   }
50009467b48Spatrick 
50109467b48Spatrick   // Now propagate info for each case value
50209467b48Spatrick   for (auto C : SI->cases()) {
50309467b48Spatrick     BasicBlock *TargetBlock = C.getCaseSuccessor();
50409467b48Spatrick     if (SwitchEdges.lookup(TargetBlock) == 1) {
50509467b48Spatrick       PredicateSwitch *PS = new PredicateSwitch(
50609467b48Spatrick           Op, SI->getParent(), TargetBlock, C.getCaseValue(), SI);
50709467b48Spatrick       addInfoFor(OpsToRename, Op, PS);
50809467b48Spatrick       if (!TargetBlock->getSinglePredecessor())
50909467b48Spatrick         EdgeUsesOnly.insert({BranchBB, TargetBlock});
51009467b48Spatrick     }
51109467b48Spatrick   }
51209467b48Spatrick }
51309467b48Spatrick 
51409467b48Spatrick // Build predicate info for our function
515097a140dSpatrick void PredicateInfoBuilder::buildPredicateInfo() {
51609467b48Spatrick   DT.updateDFSNumbers();
51709467b48Spatrick   // Collect operands to rename from all conditional branch terminators, as well
51809467b48Spatrick   // as assume statements.
51909467b48Spatrick   SmallVector<Value *, 8> OpsToRename;
52009467b48Spatrick   for (auto DTN : depth_first(DT.getRootNode())) {
52109467b48Spatrick     BasicBlock *BranchBB = DTN->getBlock();
52209467b48Spatrick     if (auto *BI = dyn_cast<BranchInst>(BranchBB->getTerminator())) {
52309467b48Spatrick       if (!BI->isConditional())
52409467b48Spatrick         continue;
52509467b48Spatrick       // Can't insert conditional information if they all go to the same place.
52609467b48Spatrick       if (BI->getSuccessor(0) == BI->getSuccessor(1))
52709467b48Spatrick         continue;
52809467b48Spatrick       processBranch(BI, BranchBB, OpsToRename);
52909467b48Spatrick     } else if (auto *SI = dyn_cast<SwitchInst>(BranchBB->getTerminator())) {
53009467b48Spatrick       processSwitch(SI, BranchBB, OpsToRename);
53109467b48Spatrick     }
53209467b48Spatrick   }
53309467b48Spatrick   for (auto &Assume : AC.assumptions()) {
53409467b48Spatrick     if (auto *II = dyn_cast_or_null<IntrinsicInst>(Assume))
53509467b48Spatrick       if (DT.isReachableFromEntry(II->getParent()))
53609467b48Spatrick         processAssume(II, II->getParent(), OpsToRename);
53709467b48Spatrick   }
53809467b48Spatrick   // Now rename all our operations.
53909467b48Spatrick   renameUses(OpsToRename);
54009467b48Spatrick }
54109467b48Spatrick 
54209467b48Spatrick // Given the renaming stack, make all the operands currently on the stack real
54309467b48Spatrick // by inserting them into the IR.  Return the last operation's value.
544097a140dSpatrick Value *PredicateInfoBuilder::materializeStack(unsigned int &Counter,
54509467b48Spatrick                                              ValueDFSStack &RenameStack,
54609467b48Spatrick                                              Value *OrigOp) {
54709467b48Spatrick   // Find the first thing we have to materialize
54809467b48Spatrick   auto RevIter = RenameStack.rbegin();
54909467b48Spatrick   for (; RevIter != RenameStack.rend(); ++RevIter)
55009467b48Spatrick     if (RevIter->Def)
55109467b48Spatrick       break;
55209467b48Spatrick 
55309467b48Spatrick   size_t Start = RevIter - RenameStack.rbegin();
55409467b48Spatrick   // The maximum number of things we should be trying to materialize at once
55509467b48Spatrick   // right now is 4, depending on if we had an assume, a branch, and both used
55609467b48Spatrick   // and of conditions.
55709467b48Spatrick   for (auto RenameIter = RenameStack.end() - Start;
55809467b48Spatrick        RenameIter != RenameStack.end(); ++RenameIter) {
55909467b48Spatrick     auto *Op =
56009467b48Spatrick         RenameIter == RenameStack.begin() ? OrigOp : (RenameIter - 1)->Def;
56109467b48Spatrick     ValueDFS &Result = *RenameIter;
56209467b48Spatrick     auto *ValInfo = Result.PInfo;
563097a140dSpatrick     ValInfo->RenamedOp = (RenameStack.end() - Start) == RenameStack.begin()
564097a140dSpatrick                              ? OrigOp
565097a140dSpatrick                              : (RenameStack.end() - Start - 1)->Def;
56609467b48Spatrick     // For edge predicates, we can just place the operand in the block before
56709467b48Spatrick     // the terminator.  For assume, we have to place it right before the assume
56809467b48Spatrick     // to ensure we dominate all of our uses.  Always insert right before the
56909467b48Spatrick     // relevant instruction (terminator, assume), so that we insert in proper
57009467b48Spatrick     // order in the case of multiple predicateinfo in the same block.
571*73471bf0Spatrick     // The number of named values is used to detect if a new declaration was
572*73471bf0Spatrick     // added. If so, that declaration is tracked so that it can be removed when
573*73471bf0Spatrick     // the analysis is done. The corner case were a new declaration results in
574*73471bf0Spatrick     // a name clash and the old name being renamed is not considered as that
575*73471bf0Spatrick     // represents an invalid module.
57609467b48Spatrick     if (isa<PredicateWithEdge>(ValInfo)) {
57709467b48Spatrick       IRBuilder<> B(getBranchTerminator(ValInfo));
578*73471bf0Spatrick       auto NumDecls = F.getParent()->getNumNamedValues();
579*73471bf0Spatrick       Function *IF = Intrinsic::getDeclaration(
580*73471bf0Spatrick           F.getParent(), Intrinsic::ssa_copy, Op->getType());
581*73471bf0Spatrick       if (NumDecls != F.getParent()->getNumNamedValues())
582097a140dSpatrick         PI.CreatedDeclarations.insert(IF);
58309467b48Spatrick       CallInst *PIC =
58409467b48Spatrick           B.CreateCall(IF, Op, Op->getName() + "." + Twine(Counter++));
585097a140dSpatrick       PI.PredicateMap.insert({PIC, ValInfo});
58609467b48Spatrick       Result.Def = PIC;
58709467b48Spatrick     } else {
58809467b48Spatrick       auto *PAssume = dyn_cast<PredicateAssume>(ValInfo);
58909467b48Spatrick       assert(PAssume &&
59009467b48Spatrick              "Should not have gotten here without it being an assume");
591097a140dSpatrick       // Insert the predicate directly after the assume. While it also holds
592097a140dSpatrick       // directly before it, assume(i1 true) is not a useful fact.
593097a140dSpatrick       IRBuilder<> B(PAssume->AssumeInst->getNextNode());
594*73471bf0Spatrick       auto NumDecls = F.getParent()->getNumNamedValues();
595*73471bf0Spatrick       Function *IF = Intrinsic::getDeclaration(
596*73471bf0Spatrick           F.getParent(), Intrinsic::ssa_copy, Op->getType());
597*73471bf0Spatrick       if (NumDecls != F.getParent()->getNumNamedValues())
598097a140dSpatrick         PI.CreatedDeclarations.insert(IF);
59909467b48Spatrick       CallInst *PIC = B.CreateCall(IF, Op);
600097a140dSpatrick       PI.PredicateMap.insert({PIC, ValInfo});
60109467b48Spatrick       Result.Def = PIC;
60209467b48Spatrick     }
60309467b48Spatrick   }
60409467b48Spatrick   return RenameStack.back().Def;
60509467b48Spatrick }
60609467b48Spatrick 
60709467b48Spatrick // Instead of the standard SSA renaming algorithm, which is O(Number of
60809467b48Spatrick // instructions), and walks the entire dominator tree, we walk only the defs +
60909467b48Spatrick // uses.  The standard SSA renaming algorithm does not really rely on the
61009467b48Spatrick // dominator tree except to order the stack push/pops of the renaming stacks, so
61109467b48Spatrick // that defs end up getting pushed before hitting the correct uses.  This does
61209467b48Spatrick // not require the dominator tree, only the *order* of the dominator tree. The
61309467b48Spatrick // complete and correct ordering of the defs and uses, in dominator tree is
61409467b48Spatrick // contained in the DFS numbering of the dominator tree. So we sort the defs and
61509467b48Spatrick // uses into the DFS ordering, and then just use the renaming stack as per
61609467b48Spatrick // normal, pushing when we hit a def (which is a predicateinfo instruction),
61709467b48Spatrick // popping when we are out of the dfs scope for that def, and replacing any uses
61809467b48Spatrick // with top of stack if it exists.  In order to handle liveness without
61909467b48Spatrick // propagating liveness info, we don't actually insert the predicateinfo
62009467b48Spatrick // instruction def until we see a use that it would dominate.  Once we see such
62109467b48Spatrick // a use, we materialize the predicateinfo instruction in the right place and
62209467b48Spatrick // use it.
62309467b48Spatrick //
62409467b48Spatrick // TODO: Use this algorithm to perform fast single-variable renaming in
62509467b48Spatrick // promotememtoreg and memoryssa.
626097a140dSpatrick void PredicateInfoBuilder::renameUses(SmallVectorImpl<Value *> &OpsToRename) {
627097a140dSpatrick   ValueDFS_Compare Compare(DT);
62809467b48Spatrick   // Compute liveness, and rename in O(uses) per Op.
62909467b48Spatrick   for (auto *Op : OpsToRename) {
63009467b48Spatrick     LLVM_DEBUG(dbgs() << "Visiting " << *Op << "\n");
63109467b48Spatrick     unsigned Counter = 0;
63209467b48Spatrick     SmallVector<ValueDFS, 16> OrderedUses;
63309467b48Spatrick     const auto &ValueInfo = getValueInfo(Op);
63409467b48Spatrick     // Insert the possible copies into the def/use list.
63509467b48Spatrick     // They will become real copies if we find a real use for them, and never
63609467b48Spatrick     // created otherwise.
63709467b48Spatrick     for (auto &PossibleCopy : ValueInfo.Infos) {
63809467b48Spatrick       ValueDFS VD;
63909467b48Spatrick       // Determine where we are going to place the copy by the copy type.
64009467b48Spatrick       // The predicate info for branches always come first, they will get
64109467b48Spatrick       // materialized in the split block at the top of the block.
64209467b48Spatrick       // The predicate info for assumes will be somewhere in the middle,
64309467b48Spatrick       // it will get materialized in front of the assume.
64409467b48Spatrick       if (const auto *PAssume = dyn_cast<PredicateAssume>(PossibleCopy)) {
64509467b48Spatrick         VD.LocalNum = LN_Middle;
64609467b48Spatrick         DomTreeNode *DomNode = DT.getNode(PAssume->AssumeInst->getParent());
64709467b48Spatrick         if (!DomNode)
64809467b48Spatrick           continue;
64909467b48Spatrick         VD.DFSIn = DomNode->getDFSNumIn();
65009467b48Spatrick         VD.DFSOut = DomNode->getDFSNumOut();
65109467b48Spatrick         VD.PInfo = PossibleCopy;
65209467b48Spatrick         OrderedUses.push_back(VD);
65309467b48Spatrick       } else if (isa<PredicateWithEdge>(PossibleCopy)) {
65409467b48Spatrick         // If we can only do phi uses, we treat it like it's in the branch
65509467b48Spatrick         // block, and handle it specially. We know that it goes last, and only
65609467b48Spatrick         // dominate phi uses.
65709467b48Spatrick         auto BlockEdge = getBlockEdge(PossibleCopy);
65809467b48Spatrick         if (EdgeUsesOnly.count(BlockEdge)) {
65909467b48Spatrick           VD.LocalNum = LN_Last;
66009467b48Spatrick           auto *DomNode = DT.getNode(BlockEdge.first);
66109467b48Spatrick           if (DomNode) {
66209467b48Spatrick             VD.DFSIn = DomNode->getDFSNumIn();
66309467b48Spatrick             VD.DFSOut = DomNode->getDFSNumOut();
66409467b48Spatrick             VD.PInfo = PossibleCopy;
66509467b48Spatrick             VD.EdgeOnly = true;
66609467b48Spatrick             OrderedUses.push_back(VD);
66709467b48Spatrick           }
66809467b48Spatrick         } else {
66909467b48Spatrick           // Otherwise, we are in the split block (even though we perform
67009467b48Spatrick           // insertion in the branch block).
67109467b48Spatrick           // Insert a possible copy at the split block and before the branch.
67209467b48Spatrick           VD.LocalNum = LN_First;
67309467b48Spatrick           auto *DomNode = DT.getNode(BlockEdge.second);
67409467b48Spatrick           if (DomNode) {
67509467b48Spatrick             VD.DFSIn = DomNode->getDFSNumIn();
67609467b48Spatrick             VD.DFSOut = DomNode->getDFSNumOut();
67709467b48Spatrick             VD.PInfo = PossibleCopy;
67809467b48Spatrick             OrderedUses.push_back(VD);
67909467b48Spatrick           }
68009467b48Spatrick         }
68109467b48Spatrick       }
68209467b48Spatrick     }
68309467b48Spatrick 
68409467b48Spatrick     convertUsesToDFSOrdered(Op, OrderedUses);
68509467b48Spatrick     // Here we require a stable sort because we do not bother to try to
68609467b48Spatrick     // assign an order to the operands the uses represent. Thus, two
68709467b48Spatrick     // uses in the same instruction do not have a strict sort order
68809467b48Spatrick     // currently and will be considered equal. We could get rid of the
68909467b48Spatrick     // stable sort by creating one if we wanted.
69009467b48Spatrick     llvm::stable_sort(OrderedUses, Compare);
69109467b48Spatrick     SmallVector<ValueDFS, 8> RenameStack;
69209467b48Spatrick     // For each use, sorted into dfs order, push values and replaces uses with
69309467b48Spatrick     // top of stack, which will represent the reaching def.
69409467b48Spatrick     for (auto &VD : OrderedUses) {
69509467b48Spatrick       // We currently do not materialize copy over copy, but we should decide if
69609467b48Spatrick       // we want to.
69709467b48Spatrick       bool PossibleCopy = VD.PInfo != nullptr;
69809467b48Spatrick       if (RenameStack.empty()) {
69909467b48Spatrick         LLVM_DEBUG(dbgs() << "Rename Stack is empty\n");
70009467b48Spatrick       } else {
70109467b48Spatrick         LLVM_DEBUG(dbgs() << "Rename Stack Top DFS numbers are ("
70209467b48Spatrick                           << RenameStack.back().DFSIn << ","
70309467b48Spatrick                           << RenameStack.back().DFSOut << ")\n");
70409467b48Spatrick       }
70509467b48Spatrick 
70609467b48Spatrick       LLVM_DEBUG(dbgs() << "Current DFS numbers are (" << VD.DFSIn << ","
70709467b48Spatrick                         << VD.DFSOut << ")\n");
70809467b48Spatrick 
70909467b48Spatrick       bool ShouldPush = (VD.Def || PossibleCopy);
71009467b48Spatrick       bool OutOfScope = !stackIsInScope(RenameStack, VD);
71109467b48Spatrick       if (OutOfScope || ShouldPush) {
71209467b48Spatrick         // Sync to our current scope.
71309467b48Spatrick         popStackUntilDFSScope(RenameStack, VD);
71409467b48Spatrick         if (ShouldPush) {
71509467b48Spatrick           RenameStack.push_back(VD);
71609467b48Spatrick         }
71709467b48Spatrick       }
71809467b48Spatrick       // If we get to this point, and the stack is empty we must have a use
71909467b48Spatrick       // with no renaming needed, just skip it.
72009467b48Spatrick       if (RenameStack.empty())
72109467b48Spatrick         continue;
72209467b48Spatrick       // Skip values, only want to rename the uses
72309467b48Spatrick       if (VD.Def || PossibleCopy)
72409467b48Spatrick         continue;
72509467b48Spatrick       if (!DebugCounter::shouldExecute(RenameCounter)) {
72609467b48Spatrick         LLVM_DEBUG(dbgs() << "Skipping execution due to debug counter\n");
72709467b48Spatrick         continue;
72809467b48Spatrick       }
72909467b48Spatrick       ValueDFS &Result = RenameStack.back();
73009467b48Spatrick 
73109467b48Spatrick       // If the possible copy dominates something, materialize our stack up to
73209467b48Spatrick       // this point. This ensures every comparison that affects our operation
73309467b48Spatrick       // ends up with predicateinfo.
73409467b48Spatrick       if (!Result.Def)
73509467b48Spatrick         Result.Def = materializeStack(Counter, RenameStack, Op);
73609467b48Spatrick 
73709467b48Spatrick       LLVM_DEBUG(dbgs() << "Found replacement " << *Result.Def << " for "
73809467b48Spatrick                         << *VD.U->get() << " in " << *(VD.U->getUser())
73909467b48Spatrick                         << "\n");
74009467b48Spatrick       assert(DT.dominates(cast<Instruction>(Result.Def), *VD.U) &&
74109467b48Spatrick              "Predicateinfo def should have dominated this use");
74209467b48Spatrick       VD.U->set(Result.Def);
74309467b48Spatrick     }
74409467b48Spatrick   }
74509467b48Spatrick }
74609467b48Spatrick 
747097a140dSpatrick PredicateInfoBuilder::ValueInfo &
748097a140dSpatrick PredicateInfoBuilder::getOrCreateValueInfo(Value *Operand) {
74909467b48Spatrick   auto OIN = ValueInfoNums.find(Operand);
75009467b48Spatrick   if (OIN == ValueInfoNums.end()) {
75109467b48Spatrick     // This will grow it
75209467b48Spatrick     ValueInfos.resize(ValueInfos.size() + 1);
75309467b48Spatrick     // This will use the new size and give us a 0 based number of the info
75409467b48Spatrick     auto InsertResult = ValueInfoNums.insert({Operand, ValueInfos.size() - 1});
75509467b48Spatrick     assert(InsertResult.second && "Value info number already existed?");
75609467b48Spatrick     return ValueInfos[InsertResult.first->second];
75709467b48Spatrick   }
75809467b48Spatrick   return ValueInfos[OIN->second];
75909467b48Spatrick }
76009467b48Spatrick 
761097a140dSpatrick const PredicateInfoBuilder::ValueInfo &
762097a140dSpatrick PredicateInfoBuilder::getValueInfo(Value *Operand) const {
76309467b48Spatrick   auto OINI = ValueInfoNums.lookup(Operand);
76409467b48Spatrick   assert(OINI != 0 && "Operand was not really in the Value Info Numbers");
76509467b48Spatrick   assert(OINI < ValueInfos.size() &&
76609467b48Spatrick          "Value Info Number greater than size of Value Info Table");
76709467b48Spatrick   return ValueInfos[OINI];
76809467b48Spatrick }
76909467b48Spatrick 
77009467b48Spatrick PredicateInfo::PredicateInfo(Function &F, DominatorTree &DT,
77109467b48Spatrick                              AssumptionCache &AC)
772097a140dSpatrick     : F(F) {
773097a140dSpatrick   PredicateInfoBuilder Builder(*this, F, DT, AC);
774097a140dSpatrick   Builder.buildPredicateInfo();
77509467b48Spatrick }
77609467b48Spatrick 
77709467b48Spatrick // Remove all declarations we created . The PredicateInfo consumers are
77809467b48Spatrick // responsible for remove the ssa_copy calls created.
77909467b48Spatrick PredicateInfo::~PredicateInfo() {
78009467b48Spatrick   // Collect function pointers in set first, as SmallSet uses a SmallVector
78109467b48Spatrick   // internally and we have to remove the asserting value handles first.
78209467b48Spatrick   SmallPtrSet<Function *, 20> FunctionPtrs;
78309467b48Spatrick   for (auto &F : CreatedDeclarations)
78409467b48Spatrick     FunctionPtrs.insert(&*F);
78509467b48Spatrick   CreatedDeclarations.clear();
78609467b48Spatrick 
78709467b48Spatrick   for (Function *F : FunctionPtrs) {
78809467b48Spatrick     assert(F->user_begin() == F->user_end() &&
78909467b48Spatrick            "PredicateInfo consumer did not remove all SSA copies.");
79009467b48Spatrick     F->eraseFromParent();
79109467b48Spatrick   }
79209467b48Spatrick }
79309467b48Spatrick 
794*73471bf0Spatrick Optional<PredicateConstraint> PredicateBase::getConstraint() const {
795*73471bf0Spatrick   switch (Type) {
796*73471bf0Spatrick   case PT_Assume:
797*73471bf0Spatrick   case PT_Branch: {
798*73471bf0Spatrick     bool TrueEdge = true;
799*73471bf0Spatrick     if (auto *PBranch = dyn_cast<PredicateBranch>(this))
800*73471bf0Spatrick       TrueEdge = PBranch->TrueEdge;
801*73471bf0Spatrick 
802*73471bf0Spatrick     if (Condition == RenamedOp) {
803*73471bf0Spatrick       return {{CmpInst::ICMP_EQ,
804*73471bf0Spatrick                TrueEdge ? ConstantInt::getTrue(Condition->getType())
805*73471bf0Spatrick                         : ConstantInt::getFalse(Condition->getType())}};
806*73471bf0Spatrick     }
807*73471bf0Spatrick 
808*73471bf0Spatrick     CmpInst *Cmp = dyn_cast<CmpInst>(Condition);
809*73471bf0Spatrick     if (!Cmp) {
810*73471bf0Spatrick       // TODO: Make this an assertion once RenamedOp is fully accurate.
811*73471bf0Spatrick       return None;
812*73471bf0Spatrick     }
813*73471bf0Spatrick 
814*73471bf0Spatrick     CmpInst::Predicate Pred;
815*73471bf0Spatrick     Value *OtherOp;
816*73471bf0Spatrick     if (Cmp->getOperand(0) == RenamedOp) {
817*73471bf0Spatrick       Pred = Cmp->getPredicate();
818*73471bf0Spatrick       OtherOp = Cmp->getOperand(1);
819*73471bf0Spatrick     } else if (Cmp->getOperand(1) == RenamedOp) {
820*73471bf0Spatrick       Pred = Cmp->getSwappedPredicate();
821*73471bf0Spatrick       OtherOp = Cmp->getOperand(0);
822*73471bf0Spatrick     } else {
823*73471bf0Spatrick       // TODO: Make this an assertion once RenamedOp is fully accurate.
824*73471bf0Spatrick       return None;
825*73471bf0Spatrick     }
826*73471bf0Spatrick 
827*73471bf0Spatrick     // Invert predicate along false edge.
828*73471bf0Spatrick     if (!TrueEdge)
829*73471bf0Spatrick       Pred = CmpInst::getInversePredicate(Pred);
830*73471bf0Spatrick 
831*73471bf0Spatrick     return {{Pred, OtherOp}};
832*73471bf0Spatrick   }
833*73471bf0Spatrick   case PT_Switch:
834*73471bf0Spatrick     if (Condition != RenamedOp) {
835*73471bf0Spatrick       // TODO: Make this an assertion once RenamedOp is fully accurate.
836*73471bf0Spatrick       return None;
837*73471bf0Spatrick     }
838*73471bf0Spatrick 
839*73471bf0Spatrick     return {{CmpInst::ICMP_EQ, cast<PredicateSwitch>(this)->CaseValue}};
840*73471bf0Spatrick   }
841*73471bf0Spatrick   llvm_unreachable("Unknown predicate type");
842*73471bf0Spatrick }
843*73471bf0Spatrick 
84409467b48Spatrick void PredicateInfo::verifyPredicateInfo() const {}
84509467b48Spatrick 
84609467b48Spatrick char PredicateInfoPrinterLegacyPass::ID = 0;
84709467b48Spatrick 
84809467b48Spatrick PredicateInfoPrinterLegacyPass::PredicateInfoPrinterLegacyPass()
84909467b48Spatrick     : FunctionPass(ID) {
85009467b48Spatrick   initializePredicateInfoPrinterLegacyPassPass(
85109467b48Spatrick       *PassRegistry::getPassRegistry());
85209467b48Spatrick }
85309467b48Spatrick 
85409467b48Spatrick void PredicateInfoPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
85509467b48Spatrick   AU.setPreservesAll();
85609467b48Spatrick   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
85709467b48Spatrick   AU.addRequired<AssumptionCacheTracker>();
85809467b48Spatrick }
85909467b48Spatrick 
86009467b48Spatrick // Replace ssa_copy calls created by PredicateInfo with their operand.
86109467b48Spatrick static void replaceCreatedSSACopys(PredicateInfo &PredInfo, Function &F) {
862*73471bf0Spatrick   for (Instruction &Inst : llvm::make_early_inc_range(instructions(F))) {
863*73471bf0Spatrick     const auto *PI = PredInfo.getPredicateInfoFor(&Inst);
864*73471bf0Spatrick     auto *II = dyn_cast<IntrinsicInst>(&Inst);
86509467b48Spatrick     if (!PI || !II || II->getIntrinsicID() != Intrinsic::ssa_copy)
86609467b48Spatrick       continue;
86709467b48Spatrick 
868*73471bf0Spatrick     Inst.replaceAllUsesWith(II->getOperand(0));
869*73471bf0Spatrick     Inst.eraseFromParent();
87009467b48Spatrick   }
87109467b48Spatrick }
87209467b48Spatrick 
87309467b48Spatrick bool PredicateInfoPrinterLegacyPass::runOnFunction(Function &F) {
87409467b48Spatrick   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
87509467b48Spatrick   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
87609467b48Spatrick   auto PredInfo = std::make_unique<PredicateInfo>(F, DT, AC);
87709467b48Spatrick   PredInfo->print(dbgs());
87809467b48Spatrick   if (VerifyPredicateInfo)
87909467b48Spatrick     PredInfo->verifyPredicateInfo();
88009467b48Spatrick 
88109467b48Spatrick   replaceCreatedSSACopys(*PredInfo, F);
88209467b48Spatrick   return false;
88309467b48Spatrick }
88409467b48Spatrick 
88509467b48Spatrick PreservedAnalyses PredicateInfoPrinterPass::run(Function &F,
88609467b48Spatrick                                                 FunctionAnalysisManager &AM) {
88709467b48Spatrick   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
88809467b48Spatrick   auto &AC = AM.getResult<AssumptionAnalysis>(F);
88909467b48Spatrick   OS << "PredicateInfo for function: " << F.getName() << "\n";
89009467b48Spatrick   auto PredInfo = std::make_unique<PredicateInfo>(F, DT, AC);
89109467b48Spatrick   PredInfo->print(OS);
89209467b48Spatrick 
89309467b48Spatrick   replaceCreatedSSACopys(*PredInfo, F);
89409467b48Spatrick   return PreservedAnalyses::all();
89509467b48Spatrick }
89609467b48Spatrick 
89709467b48Spatrick /// An assembly annotator class to print PredicateInfo information in
89809467b48Spatrick /// comments.
89909467b48Spatrick class PredicateInfoAnnotatedWriter : public AssemblyAnnotationWriter {
90009467b48Spatrick   friend class PredicateInfo;
90109467b48Spatrick   const PredicateInfo *PredInfo;
90209467b48Spatrick 
90309467b48Spatrick public:
90409467b48Spatrick   PredicateInfoAnnotatedWriter(const PredicateInfo *M) : PredInfo(M) {}
90509467b48Spatrick 
906097a140dSpatrick   void emitBasicBlockStartAnnot(const BasicBlock *BB,
907097a140dSpatrick                                 formatted_raw_ostream &OS) override {}
90809467b48Spatrick 
909097a140dSpatrick   void emitInstructionAnnot(const Instruction *I,
910097a140dSpatrick                             formatted_raw_ostream &OS) override {
91109467b48Spatrick     if (const auto *PI = PredInfo->getPredicateInfoFor(I)) {
91209467b48Spatrick       OS << "; Has predicate info\n";
91309467b48Spatrick       if (const auto *PB = dyn_cast<PredicateBranch>(PI)) {
91409467b48Spatrick         OS << "; branch predicate info { TrueEdge: " << PB->TrueEdge
91509467b48Spatrick            << " Comparison:" << *PB->Condition << " Edge: [";
91609467b48Spatrick         PB->From->printAsOperand(OS);
91709467b48Spatrick         OS << ",";
91809467b48Spatrick         PB->To->printAsOperand(OS);
919097a140dSpatrick         OS << "]";
92009467b48Spatrick       } else if (const auto *PS = dyn_cast<PredicateSwitch>(PI)) {
92109467b48Spatrick         OS << "; switch predicate info { CaseValue: " << *PS->CaseValue
92209467b48Spatrick            << " Switch:" << *PS->Switch << " Edge: [";
92309467b48Spatrick         PS->From->printAsOperand(OS);
92409467b48Spatrick         OS << ",";
92509467b48Spatrick         PS->To->printAsOperand(OS);
926097a140dSpatrick         OS << "]";
92709467b48Spatrick       } else if (const auto *PA = dyn_cast<PredicateAssume>(PI)) {
92809467b48Spatrick         OS << "; assume predicate info {"
929097a140dSpatrick            << " Comparison:" << *PA->Condition;
93009467b48Spatrick       }
931097a140dSpatrick       OS << ", RenamedOp: ";
932097a140dSpatrick       PI->RenamedOp->printAsOperand(OS, false);
933097a140dSpatrick       OS << " }\n";
93409467b48Spatrick     }
93509467b48Spatrick   }
93609467b48Spatrick };
93709467b48Spatrick 
93809467b48Spatrick void PredicateInfo::print(raw_ostream &OS) const {
93909467b48Spatrick   PredicateInfoAnnotatedWriter Writer(this);
94009467b48Spatrick   F.print(OS, &Writer);
94109467b48Spatrick }
94209467b48Spatrick 
94309467b48Spatrick void PredicateInfo::dump() const {
94409467b48Spatrick   PredicateInfoAnnotatedWriter Writer(this);
94509467b48Spatrick   F.print(dbgs(), &Writer);
94609467b48Spatrick }
94709467b48Spatrick 
94809467b48Spatrick PreservedAnalyses PredicateInfoVerifierPass::run(Function &F,
94909467b48Spatrick                                                  FunctionAnalysisManager &AM) {
95009467b48Spatrick   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
95109467b48Spatrick   auto &AC = AM.getResult<AssumptionAnalysis>(F);
95209467b48Spatrick   std::make_unique<PredicateInfo>(F, DT, AC)->verifyPredicateInfo();
95309467b48Spatrick 
95409467b48Spatrick   return PreservedAnalyses::all();
95509467b48Spatrick }
95609467b48Spatrick }
957