xref: /openbsd-src/gnu/llvm/llvm/lib/Transforms/Utils/PredicateInfo.cpp (revision 09467b48e8bc8b4905716062da846024139afbf2)
1*09467b48Spatrick //===-- PredicateInfo.cpp - PredicateInfo Builder--------------------===//
2*09467b48Spatrick //
3*09467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*09467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
5*09467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*09467b48Spatrick //
7*09467b48Spatrick //===----------------------------------------------------------------===//
8*09467b48Spatrick //
9*09467b48Spatrick // This file implements the PredicateInfo class.
10*09467b48Spatrick //
11*09467b48Spatrick //===----------------------------------------------------------------===//
12*09467b48Spatrick 
13*09467b48Spatrick #include "llvm/Transforms/Utils/PredicateInfo.h"
14*09467b48Spatrick #include "llvm/ADT/DenseMap.h"
15*09467b48Spatrick #include "llvm/ADT/DepthFirstIterator.h"
16*09467b48Spatrick #include "llvm/ADT/STLExtras.h"
17*09467b48Spatrick #include "llvm/ADT/SmallPtrSet.h"
18*09467b48Spatrick #include "llvm/ADT/Statistic.h"
19*09467b48Spatrick #include "llvm/ADT/StringExtras.h"
20*09467b48Spatrick #include "llvm/Analysis/AssumptionCache.h"
21*09467b48Spatrick #include "llvm/Analysis/CFG.h"
22*09467b48Spatrick #include "llvm/IR/AssemblyAnnotationWriter.h"
23*09467b48Spatrick #include "llvm/IR/DataLayout.h"
24*09467b48Spatrick #include "llvm/IR/Dominators.h"
25*09467b48Spatrick #include "llvm/IR/GlobalVariable.h"
26*09467b48Spatrick #include "llvm/IR/IRBuilder.h"
27*09467b48Spatrick #include "llvm/IR/InstIterator.h"
28*09467b48Spatrick #include "llvm/IR/IntrinsicInst.h"
29*09467b48Spatrick #include "llvm/IR/LLVMContext.h"
30*09467b48Spatrick #include "llvm/IR/Metadata.h"
31*09467b48Spatrick #include "llvm/IR/Module.h"
32*09467b48Spatrick #include "llvm/IR/PatternMatch.h"
33*09467b48Spatrick #include "llvm/InitializePasses.h"
34*09467b48Spatrick #include "llvm/Support/Debug.h"
35*09467b48Spatrick #include "llvm/Support/DebugCounter.h"
36*09467b48Spatrick #include "llvm/Support/FormattedStream.h"
37*09467b48Spatrick #include "llvm/Transforms/Utils.h"
38*09467b48Spatrick #include <algorithm>
39*09467b48Spatrick #define DEBUG_TYPE "predicateinfo"
40*09467b48Spatrick using namespace llvm;
41*09467b48Spatrick using namespace PatternMatch;
42*09467b48Spatrick using namespace llvm::PredicateInfoClasses;
43*09467b48Spatrick 
44*09467b48Spatrick INITIALIZE_PASS_BEGIN(PredicateInfoPrinterLegacyPass, "print-predicateinfo",
45*09467b48Spatrick                       "PredicateInfo Printer", false, false)
46*09467b48Spatrick INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
47*09467b48Spatrick INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
48*09467b48Spatrick INITIALIZE_PASS_END(PredicateInfoPrinterLegacyPass, "print-predicateinfo",
49*09467b48Spatrick                     "PredicateInfo Printer", false, false)
50*09467b48Spatrick static cl::opt<bool> VerifyPredicateInfo(
51*09467b48Spatrick     "verify-predicateinfo", cl::init(false), cl::Hidden,
52*09467b48Spatrick     cl::desc("Verify PredicateInfo in legacy printer pass."));
53*09467b48Spatrick DEBUG_COUNTER(RenameCounter, "predicateinfo-rename",
54*09467b48Spatrick               "Controls which variables are renamed with predicateinfo");
55*09467b48Spatrick 
56*09467b48Spatrick namespace {
57*09467b48Spatrick // Given a predicate info that is a type of branching terminator, get the
58*09467b48Spatrick // branching block.
59*09467b48Spatrick const BasicBlock *getBranchBlock(const PredicateBase *PB) {
60*09467b48Spatrick   assert(isa<PredicateWithEdge>(PB) &&
61*09467b48Spatrick          "Only branches and switches should have PHIOnly defs that "
62*09467b48Spatrick          "require branch blocks.");
63*09467b48Spatrick   return cast<PredicateWithEdge>(PB)->From;
64*09467b48Spatrick }
65*09467b48Spatrick 
66*09467b48Spatrick // Given a predicate info that is a type of branching terminator, get the
67*09467b48Spatrick // branching terminator.
68*09467b48Spatrick static Instruction *getBranchTerminator(const PredicateBase *PB) {
69*09467b48Spatrick   assert(isa<PredicateWithEdge>(PB) &&
70*09467b48Spatrick          "Not a predicate info type we know how to get a terminator from.");
71*09467b48Spatrick   return cast<PredicateWithEdge>(PB)->From->getTerminator();
72*09467b48Spatrick }
73*09467b48Spatrick 
74*09467b48Spatrick // Given a predicate info that is a type of branching terminator, get the
75*09467b48Spatrick // edge this predicate info represents
76*09467b48Spatrick const std::pair<BasicBlock *, BasicBlock *>
77*09467b48Spatrick getBlockEdge(const PredicateBase *PB) {
78*09467b48Spatrick   assert(isa<PredicateWithEdge>(PB) &&
79*09467b48Spatrick          "Not a predicate info type we know how to get an edge from.");
80*09467b48Spatrick   const auto *PEdge = cast<PredicateWithEdge>(PB);
81*09467b48Spatrick   return std::make_pair(PEdge->From, PEdge->To);
82*09467b48Spatrick }
83*09467b48Spatrick }
84*09467b48Spatrick 
85*09467b48Spatrick namespace llvm {
86*09467b48Spatrick namespace PredicateInfoClasses {
87*09467b48Spatrick enum LocalNum {
88*09467b48Spatrick   // Operations that must appear first in the block.
89*09467b48Spatrick   LN_First,
90*09467b48Spatrick   // Operations that are somewhere in the middle of the block, and are sorted on
91*09467b48Spatrick   // demand.
92*09467b48Spatrick   LN_Middle,
93*09467b48Spatrick   // Operations that must appear last in a block, like successor phi node uses.
94*09467b48Spatrick   LN_Last
95*09467b48Spatrick };
96*09467b48Spatrick 
97*09467b48Spatrick // Associate global and local DFS info with defs and uses, so we can sort them
98*09467b48Spatrick // into a global domination ordering.
99*09467b48Spatrick struct ValueDFS {
100*09467b48Spatrick   int DFSIn = 0;
101*09467b48Spatrick   int DFSOut = 0;
102*09467b48Spatrick   unsigned int LocalNum = LN_Middle;
103*09467b48Spatrick   // Only one of Def or Use will be set.
104*09467b48Spatrick   Value *Def = nullptr;
105*09467b48Spatrick   Use *U = nullptr;
106*09467b48Spatrick   // Neither PInfo nor EdgeOnly participate in the ordering
107*09467b48Spatrick   PredicateBase *PInfo = nullptr;
108*09467b48Spatrick   bool EdgeOnly = false;
109*09467b48Spatrick };
110*09467b48Spatrick 
111*09467b48Spatrick // Perform a strict weak ordering on instructions and arguments.
112*09467b48Spatrick static bool valueComesBefore(OrderedInstructions &OI, const Value *A,
113*09467b48Spatrick                              const Value *B) {
114*09467b48Spatrick   auto *ArgA = dyn_cast_or_null<Argument>(A);
115*09467b48Spatrick   auto *ArgB = dyn_cast_or_null<Argument>(B);
116*09467b48Spatrick   if (ArgA && !ArgB)
117*09467b48Spatrick     return true;
118*09467b48Spatrick   if (ArgB && !ArgA)
119*09467b48Spatrick     return false;
120*09467b48Spatrick   if (ArgA && ArgB)
121*09467b48Spatrick     return ArgA->getArgNo() < ArgB->getArgNo();
122*09467b48Spatrick   return OI.dfsBefore(cast<Instruction>(A), cast<Instruction>(B));
123*09467b48Spatrick }
124*09467b48Spatrick 
125*09467b48Spatrick // This compares ValueDFS structures, creating OrderedBasicBlocks where
126*09467b48Spatrick // necessary to compare uses/defs in the same block.  Doing so allows us to walk
127*09467b48Spatrick // the minimum number of instructions necessary to compute our def/use ordering.
128*09467b48Spatrick struct ValueDFS_Compare {
129*09467b48Spatrick   DominatorTree &DT;
130*09467b48Spatrick   OrderedInstructions &OI;
131*09467b48Spatrick   ValueDFS_Compare(DominatorTree &DT, OrderedInstructions &OI)
132*09467b48Spatrick       : DT(DT), OI(OI) {}
133*09467b48Spatrick 
134*09467b48Spatrick   bool operator()(const ValueDFS &A, const ValueDFS &B) const {
135*09467b48Spatrick     if (&A == &B)
136*09467b48Spatrick       return false;
137*09467b48Spatrick     // The only case we can't directly compare them is when they in the same
138*09467b48Spatrick     // block, and both have localnum == middle.  In that case, we have to use
139*09467b48Spatrick     // comesbefore to see what the real ordering is, because they are in the
140*09467b48Spatrick     // same basic block.
141*09467b48Spatrick 
142*09467b48Spatrick     assert((A.DFSIn != B.DFSIn || A.DFSOut == B.DFSOut) &&
143*09467b48Spatrick            "Equal DFS-in numbers imply equal out numbers");
144*09467b48Spatrick     bool SameBlock = A.DFSIn == B.DFSIn;
145*09467b48Spatrick 
146*09467b48Spatrick     // We want to put the def that will get used for a given set of phi uses,
147*09467b48Spatrick     // before those phi uses.
148*09467b48Spatrick     // So we sort by edge, then by def.
149*09467b48Spatrick     // Note that only phi nodes uses and defs can come last.
150*09467b48Spatrick     if (SameBlock && A.LocalNum == LN_Last && B.LocalNum == LN_Last)
151*09467b48Spatrick       return comparePHIRelated(A, B);
152*09467b48Spatrick 
153*09467b48Spatrick     bool isADef = A.Def;
154*09467b48Spatrick     bool isBDef = B.Def;
155*09467b48Spatrick     if (!SameBlock || A.LocalNum != LN_Middle || B.LocalNum != LN_Middle)
156*09467b48Spatrick       return std::tie(A.DFSIn, A.LocalNum, isADef) <
157*09467b48Spatrick              std::tie(B.DFSIn, B.LocalNum, isBDef);
158*09467b48Spatrick     return localComesBefore(A, B);
159*09467b48Spatrick   }
160*09467b48Spatrick 
161*09467b48Spatrick   // For a phi use, or a non-materialized def, return the edge it represents.
162*09467b48Spatrick   const std::pair<BasicBlock *, BasicBlock *>
163*09467b48Spatrick   getBlockEdge(const ValueDFS &VD) const {
164*09467b48Spatrick     if (!VD.Def && VD.U) {
165*09467b48Spatrick       auto *PHI = cast<PHINode>(VD.U->getUser());
166*09467b48Spatrick       return std::make_pair(PHI->getIncomingBlock(*VD.U), PHI->getParent());
167*09467b48Spatrick     }
168*09467b48Spatrick     // This is really a non-materialized def.
169*09467b48Spatrick     return ::getBlockEdge(VD.PInfo);
170*09467b48Spatrick   }
171*09467b48Spatrick 
172*09467b48Spatrick   // For two phi related values, return the ordering.
173*09467b48Spatrick   bool comparePHIRelated(const ValueDFS &A, const ValueDFS &B) const {
174*09467b48Spatrick     BasicBlock *ASrc, *ADest, *BSrc, *BDest;
175*09467b48Spatrick     std::tie(ASrc, ADest) = getBlockEdge(A);
176*09467b48Spatrick     std::tie(BSrc, BDest) = getBlockEdge(B);
177*09467b48Spatrick 
178*09467b48Spatrick #ifndef NDEBUG
179*09467b48Spatrick     // This function should only be used for values in the same BB, check that.
180*09467b48Spatrick     DomTreeNode *DomASrc = DT.getNode(ASrc);
181*09467b48Spatrick     DomTreeNode *DomBSrc = DT.getNode(BSrc);
182*09467b48Spatrick     assert(DomASrc->getDFSNumIn() == (unsigned)A.DFSIn &&
183*09467b48Spatrick            "DFS numbers for A should match the ones of the source block");
184*09467b48Spatrick     assert(DomBSrc->getDFSNumIn() == (unsigned)B.DFSIn &&
185*09467b48Spatrick            "DFS numbers for B should match the ones of the source block");
186*09467b48Spatrick     assert(A.DFSIn == B.DFSIn && "Values must be in the same block");
187*09467b48Spatrick #endif
188*09467b48Spatrick     (void)ASrc;
189*09467b48Spatrick     (void)BSrc;
190*09467b48Spatrick 
191*09467b48Spatrick     // Use DFS numbers to compare destination blocks, to guarantee a
192*09467b48Spatrick     // deterministic order.
193*09467b48Spatrick     DomTreeNode *DomADest = DT.getNode(ADest);
194*09467b48Spatrick     DomTreeNode *DomBDest = DT.getNode(BDest);
195*09467b48Spatrick     unsigned AIn = DomADest->getDFSNumIn();
196*09467b48Spatrick     unsigned BIn = DomBDest->getDFSNumIn();
197*09467b48Spatrick     bool isADef = A.Def;
198*09467b48Spatrick     bool isBDef = B.Def;
199*09467b48Spatrick     assert((!A.Def || !A.U) && (!B.Def || !B.U) &&
200*09467b48Spatrick            "Def and U cannot be set at the same time");
201*09467b48Spatrick     // Now sort by edge destination and then defs before uses.
202*09467b48Spatrick     return std::tie(AIn, isADef) < std::tie(BIn, isBDef);
203*09467b48Spatrick   }
204*09467b48Spatrick 
205*09467b48Spatrick   // Get the definition of an instruction that occurs in the middle of a block.
206*09467b48Spatrick   Value *getMiddleDef(const ValueDFS &VD) const {
207*09467b48Spatrick     if (VD.Def)
208*09467b48Spatrick       return VD.Def;
209*09467b48Spatrick     // It's possible for the defs and uses to be null.  For branches, the local
210*09467b48Spatrick     // numbering will say the placed predicaeinfos should go first (IE
211*09467b48Spatrick     // LN_beginning), so we won't be in this function. For assumes, we will end
212*09467b48Spatrick     // up here, beause we need to order the def we will place relative to the
213*09467b48Spatrick     // assume.  So for the purpose of ordering, we pretend the def is the assume
214*09467b48Spatrick     // because that is where we will insert the info.
215*09467b48Spatrick     if (!VD.U) {
216*09467b48Spatrick       assert(VD.PInfo &&
217*09467b48Spatrick              "No def, no use, and no predicateinfo should not occur");
218*09467b48Spatrick       assert(isa<PredicateAssume>(VD.PInfo) &&
219*09467b48Spatrick              "Middle of block should only occur for assumes");
220*09467b48Spatrick       return cast<PredicateAssume>(VD.PInfo)->AssumeInst;
221*09467b48Spatrick     }
222*09467b48Spatrick     return nullptr;
223*09467b48Spatrick   }
224*09467b48Spatrick 
225*09467b48Spatrick   // Return either the Def, if it's not null, or the user of the Use, if the def
226*09467b48Spatrick   // is null.
227*09467b48Spatrick   const Instruction *getDefOrUser(const Value *Def, const Use *U) const {
228*09467b48Spatrick     if (Def)
229*09467b48Spatrick       return cast<Instruction>(Def);
230*09467b48Spatrick     return cast<Instruction>(U->getUser());
231*09467b48Spatrick   }
232*09467b48Spatrick 
233*09467b48Spatrick   // This performs the necessary local basic block ordering checks to tell
234*09467b48Spatrick   // whether A comes before B, where both are in the same basic block.
235*09467b48Spatrick   bool localComesBefore(const ValueDFS &A, const ValueDFS &B) const {
236*09467b48Spatrick     auto *ADef = getMiddleDef(A);
237*09467b48Spatrick     auto *BDef = getMiddleDef(B);
238*09467b48Spatrick 
239*09467b48Spatrick     // See if we have real values or uses. If we have real values, we are
240*09467b48Spatrick     // guaranteed they are instructions or arguments. No matter what, we are
241*09467b48Spatrick     // guaranteed they are in the same block if they are instructions.
242*09467b48Spatrick     auto *ArgA = dyn_cast_or_null<Argument>(ADef);
243*09467b48Spatrick     auto *ArgB = dyn_cast_or_null<Argument>(BDef);
244*09467b48Spatrick 
245*09467b48Spatrick     if (ArgA || ArgB)
246*09467b48Spatrick       return valueComesBefore(OI, ArgA, ArgB);
247*09467b48Spatrick 
248*09467b48Spatrick     auto *AInst = getDefOrUser(ADef, A.U);
249*09467b48Spatrick     auto *BInst = getDefOrUser(BDef, B.U);
250*09467b48Spatrick     return valueComesBefore(OI, AInst, BInst);
251*09467b48Spatrick   }
252*09467b48Spatrick };
253*09467b48Spatrick 
254*09467b48Spatrick } // namespace PredicateInfoClasses
255*09467b48Spatrick 
256*09467b48Spatrick bool PredicateInfo::stackIsInScope(const ValueDFSStack &Stack,
257*09467b48Spatrick                                    const ValueDFS &VDUse) const {
258*09467b48Spatrick   if (Stack.empty())
259*09467b48Spatrick     return false;
260*09467b48Spatrick   // If it's a phi only use, make sure it's for this phi node edge, and that the
261*09467b48Spatrick   // use is in a phi node.  If it's anything else, and the top of the stack is
262*09467b48Spatrick   // EdgeOnly, we need to pop the stack.  We deliberately sort phi uses next to
263*09467b48Spatrick   // the defs they must go with so that we can know it's time to pop the stack
264*09467b48Spatrick   // when we hit the end of the phi uses for a given def.
265*09467b48Spatrick   if (Stack.back().EdgeOnly) {
266*09467b48Spatrick     if (!VDUse.U)
267*09467b48Spatrick       return false;
268*09467b48Spatrick     auto *PHI = dyn_cast<PHINode>(VDUse.U->getUser());
269*09467b48Spatrick     if (!PHI)
270*09467b48Spatrick       return false;
271*09467b48Spatrick     // Check edge
272*09467b48Spatrick     BasicBlock *EdgePred = PHI->getIncomingBlock(*VDUse.U);
273*09467b48Spatrick     if (EdgePred != getBranchBlock(Stack.back().PInfo))
274*09467b48Spatrick       return false;
275*09467b48Spatrick 
276*09467b48Spatrick     // Use dominates, which knows how to handle edge dominance.
277*09467b48Spatrick     return DT.dominates(getBlockEdge(Stack.back().PInfo), *VDUse.U);
278*09467b48Spatrick   }
279*09467b48Spatrick 
280*09467b48Spatrick   return (VDUse.DFSIn >= Stack.back().DFSIn &&
281*09467b48Spatrick           VDUse.DFSOut <= Stack.back().DFSOut);
282*09467b48Spatrick }
283*09467b48Spatrick 
284*09467b48Spatrick void PredicateInfo::popStackUntilDFSScope(ValueDFSStack &Stack,
285*09467b48Spatrick                                           const ValueDFS &VD) {
286*09467b48Spatrick   while (!Stack.empty() && !stackIsInScope(Stack, VD))
287*09467b48Spatrick     Stack.pop_back();
288*09467b48Spatrick }
289*09467b48Spatrick 
290*09467b48Spatrick // Convert the uses of Op into a vector of uses, associating global and local
291*09467b48Spatrick // DFS info with each one.
292*09467b48Spatrick void PredicateInfo::convertUsesToDFSOrdered(
293*09467b48Spatrick     Value *Op, SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
294*09467b48Spatrick   for (auto &U : Op->uses()) {
295*09467b48Spatrick     if (auto *I = dyn_cast<Instruction>(U.getUser())) {
296*09467b48Spatrick       ValueDFS VD;
297*09467b48Spatrick       // Put the phi node uses in the incoming block.
298*09467b48Spatrick       BasicBlock *IBlock;
299*09467b48Spatrick       if (auto *PN = dyn_cast<PHINode>(I)) {
300*09467b48Spatrick         IBlock = PN->getIncomingBlock(U);
301*09467b48Spatrick         // Make phi node users appear last in the incoming block
302*09467b48Spatrick         // they are from.
303*09467b48Spatrick         VD.LocalNum = LN_Last;
304*09467b48Spatrick       } else {
305*09467b48Spatrick         // If it's not a phi node use, it is somewhere in the middle of the
306*09467b48Spatrick         // block.
307*09467b48Spatrick         IBlock = I->getParent();
308*09467b48Spatrick         VD.LocalNum = LN_Middle;
309*09467b48Spatrick       }
310*09467b48Spatrick       DomTreeNode *DomNode = DT.getNode(IBlock);
311*09467b48Spatrick       // It's possible our use is in an unreachable block. Skip it if so.
312*09467b48Spatrick       if (!DomNode)
313*09467b48Spatrick         continue;
314*09467b48Spatrick       VD.DFSIn = DomNode->getDFSNumIn();
315*09467b48Spatrick       VD.DFSOut = DomNode->getDFSNumOut();
316*09467b48Spatrick       VD.U = &U;
317*09467b48Spatrick       DFSOrderedSet.push_back(VD);
318*09467b48Spatrick     }
319*09467b48Spatrick   }
320*09467b48Spatrick }
321*09467b48Spatrick 
322*09467b48Spatrick // Collect relevant operations from Comparison that we may want to insert copies
323*09467b48Spatrick // for.
324*09467b48Spatrick void collectCmpOps(CmpInst *Comparison, SmallVectorImpl<Value *> &CmpOperands) {
325*09467b48Spatrick   auto *Op0 = Comparison->getOperand(0);
326*09467b48Spatrick   auto *Op1 = Comparison->getOperand(1);
327*09467b48Spatrick   if (Op0 == Op1)
328*09467b48Spatrick     return;
329*09467b48Spatrick   CmpOperands.push_back(Comparison);
330*09467b48Spatrick   // Only want real values, not constants.  Additionally, operands with one use
331*09467b48Spatrick   // are only being used in the comparison, which means they will not be useful
332*09467b48Spatrick   // for us to consider for predicateinfo.
333*09467b48Spatrick   //
334*09467b48Spatrick   if ((isa<Instruction>(Op0) || isa<Argument>(Op0)) && !Op0->hasOneUse())
335*09467b48Spatrick     CmpOperands.push_back(Op0);
336*09467b48Spatrick   if ((isa<Instruction>(Op1) || isa<Argument>(Op1)) && !Op1->hasOneUse())
337*09467b48Spatrick     CmpOperands.push_back(Op1);
338*09467b48Spatrick }
339*09467b48Spatrick 
340*09467b48Spatrick // Add Op, PB to the list of value infos for Op, and mark Op to be renamed.
341*09467b48Spatrick void PredicateInfo::addInfoFor(SmallVectorImpl<Value *> &OpsToRename, Value *Op,
342*09467b48Spatrick                                PredicateBase *PB) {
343*09467b48Spatrick   auto &OperandInfo = getOrCreateValueInfo(Op);
344*09467b48Spatrick   if (OperandInfo.Infos.empty())
345*09467b48Spatrick     OpsToRename.push_back(Op);
346*09467b48Spatrick   AllInfos.push_back(PB);
347*09467b48Spatrick   OperandInfo.Infos.push_back(PB);
348*09467b48Spatrick }
349*09467b48Spatrick 
350*09467b48Spatrick // Process an assume instruction and place relevant operations we want to rename
351*09467b48Spatrick // into OpsToRename.
352*09467b48Spatrick void PredicateInfo::processAssume(IntrinsicInst *II, BasicBlock *AssumeBB,
353*09467b48Spatrick                                   SmallVectorImpl<Value *> &OpsToRename) {
354*09467b48Spatrick   // See if we have a comparison we support
355*09467b48Spatrick   SmallVector<Value *, 8> CmpOperands;
356*09467b48Spatrick   SmallVector<Value *, 2> ConditionsToProcess;
357*09467b48Spatrick   CmpInst::Predicate Pred;
358*09467b48Spatrick   Value *Operand = II->getOperand(0);
359*09467b48Spatrick   if (m_c_And(m_Cmp(Pred, m_Value(), m_Value()),
360*09467b48Spatrick               m_Cmp(Pred, m_Value(), m_Value()))
361*09467b48Spatrick           .match(II->getOperand(0))) {
362*09467b48Spatrick     ConditionsToProcess.push_back(cast<BinaryOperator>(Operand)->getOperand(0));
363*09467b48Spatrick     ConditionsToProcess.push_back(cast<BinaryOperator>(Operand)->getOperand(1));
364*09467b48Spatrick     ConditionsToProcess.push_back(Operand);
365*09467b48Spatrick   } else if (isa<CmpInst>(Operand)) {
366*09467b48Spatrick 
367*09467b48Spatrick     ConditionsToProcess.push_back(Operand);
368*09467b48Spatrick   }
369*09467b48Spatrick   for (auto Cond : ConditionsToProcess) {
370*09467b48Spatrick     if (auto *Cmp = dyn_cast<CmpInst>(Cond)) {
371*09467b48Spatrick       collectCmpOps(Cmp, CmpOperands);
372*09467b48Spatrick       // Now add our copy infos for our operands
373*09467b48Spatrick       for (auto *Op : CmpOperands) {
374*09467b48Spatrick         auto *PA = new PredicateAssume(Op, II, Cmp);
375*09467b48Spatrick         addInfoFor(OpsToRename, Op, PA);
376*09467b48Spatrick       }
377*09467b48Spatrick       CmpOperands.clear();
378*09467b48Spatrick     } else if (auto *BinOp = dyn_cast<BinaryOperator>(Cond)) {
379*09467b48Spatrick       // Otherwise, it should be an AND.
380*09467b48Spatrick       assert(BinOp->getOpcode() == Instruction::And &&
381*09467b48Spatrick              "Should have been an AND");
382*09467b48Spatrick       auto *PA = new PredicateAssume(BinOp, II, BinOp);
383*09467b48Spatrick       addInfoFor(OpsToRename, BinOp, PA);
384*09467b48Spatrick     } else {
385*09467b48Spatrick       llvm_unreachable("Unknown type of condition");
386*09467b48Spatrick     }
387*09467b48Spatrick   }
388*09467b48Spatrick }
389*09467b48Spatrick 
390*09467b48Spatrick // Process a block terminating branch, and place relevant operations to be
391*09467b48Spatrick // renamed into OpsToRename.
392*09467b48Spatrick void PredicateInfo::processBranch(BranchInst *BI, BasicBlock *BranchBB,
393*09467b48Spatrick                                   SmallVectorImpl<Value *> &OpsToRename) {
394*09467b48Spatrick   BasicBlock *FirstBB = BI->getSuccessor(0);
395*09467b48Spatrick   BasicBlock *SecondBB = BI->getSuccessor(1);
396*09467b48Spatrick   SmallVector<BasicBlock *, 2> SuccsToProcess;
397*09467b48Spatrick   SuccsToProcess.push_back(FirstBB);
398*09467b48Spatrick   SuccsToProcess.push_back(SecondBB);
399*09467b48Spatrick   SmallVector<Value *, 2> ConditionsToProcess;
400*09467b48Spatrick 
401*09467b48Spatrick   auto InsertHelper = [&](Value *Op, bool isAnd, bool isOr, Value *Cond) {
402*09467b48Spatrick     for (auto *Succ : SuccsToProcess) {
403*09467b48Spatrick       // Don't try to insert on a self-edge. This is mainly because we will
404*09467b48Spatrick       // eliminate during renaming anyway.
405*09467b48Spatrick       if (Succ == BranchBB)
406*09467b48Spatrick         continue;
407*09467b48Spatrick       bool TakenEdge = (Succ == FirstBB);
408*09467b48Spatrick       // For and, only insert on the true edge
409*09467b48Spatrick       // For or, only insert on the false edge
410*09467b48Spatrick       if ((isAnd && !TakenEdge) || (isOr && TakenEdge))
411*09467b48Spatrick         continue;
412*09467b48Spatrick       PredicateBase *PB =
413*09467b48Spatrick           new PredicateBranch(Op, BranchBB, Succ, Cond, TakenEdge);
414*09467b48Spatrick       addInfoFor(OpsToRename, Op, PB);
415*09467b48Spatrick       if (!Succ->getSinglePredecessor())
416*09467b48Spatrick         EdgeUsesOnly.insert({BranchBB, Succ});
417*09467b48Spatrick     }
418*09467b48Spatrick   };
419*09467b48Spatrick 
420*09467b48Spatrick   // Match combinations of conditions.
421*09467b48Spatrick   CmpInst::Predicate Pred;
422*09467b48Spatrick   bool isAnd = false;
423*09467b48Spatrick   bool isOr = false;
424*09467b48Spatrick   SmallVector<Value *, 8> CmpOperands;
425*09467b48Spatrick   if (match(BI->getCondition(), m_And(m_Cmp(Pred, m_Value(), m_Value()),
426*09467b48Spatrick                                       m_Cmp(Pred, m_Value(), m_Value()))) ||
427*09467b48Spatrick       match(BI->getCondition(), m_Or(m_Cmp(Pred, m_Value(), m_Value()),
428*09467b48Spatrick                                      m_Cmp(Pred, m_Value(), m_Value())))) {
429*09467b48Spatrick     auto *BinOp = cast<BinaryOperator>(BI->getCondition());
430*09467b48Spatrick     if (BinOp->getOpcode() == Instruction::And)
431*09467b48Spatrick       isAnd = true;
432*09467b48Spatrick     else if (BinOp->getOpcode() == Instruction::Or)
433*09467b48Spatrick       isOr = true;
434*09467b48Spatrick     ConditionsToProcess.push_back(BinOp->getOperand(0));
435*09467b48Spatrick     ConditionsToProcess.push_back(BinOp->getOperand(1));
436*09467b48Spatrick     ConditionsToProcess.push_back(BI->getCondition());
437*09467b48Spatrick   } else if (isa<CmpInst>(BI->getCondition())) {
438*09467b48Spatrick     ConditionsToProcess.push_back(BI->getCondition());
439*09467b48Spatrick   }
440*09467b48Spatrick   for (auto Cond : ConditionsToProcess) {
441*09467b48Spatrick     if (auto *Cmp = dyn_cast<CmpInst>(Cond)) {
442*09467b48Spatrick       collectCmpOps(Cmp, CmpOperands);
443*09467b48Spatrick       // Now add our copy infos for our operands
444*09467b48Spatrick       for (auto *Op : CmpOperands)
445*09467b48Spatrick         InsertHelper(Op, isAnd, isOr, Cmp);
446*09467b48Spatrick     } else if (auto *BinOp = dyn_cast<BinaryOperator>(Cond)) {
447*09467b48Spatrick       // This must be an AND or an OR.
448*09467b48Spatrick       assert((BinOp->getOpcode() == Instruction::And ||
449*09467b48Spatrick               BinOp->getOpcode() == Instruction::Or) &&
450*09467b48Spatrick              "Should have been an AND or an OR");
451*09467b48Spatrick       // The actual value of the binop is not subject to the same restrictions
452*09467b48Spatrick       // as the comparison. It's either true or false on the true/false branch.
453*09467b48Spatrick       InsertHelper(BinOp, false, false, BinOp);
454*09467b48Spatrick     } else {
455*09467b48Spatrick       llvm_unreachable("Unknown type of condition");
456*09467b48Spatrick     }
457*09467b48Spatrick     CmpOperands.clear();
458*09467b48Spatrick   }
459*09467b48Spatrick }
460*09467b48Spatrick // Process a block terminating switch, and place relevant operations to be
461*09467b48Spatrick // renamed into OpsToRename.
462*09467b48Spatrick void PredicateInfo::processSwitch(SwitchInst *SI, BasicBlock *BranchBB,
463*09467b48Spatrick                                   SmallVectorImpl<Value *> &OpsToRename) {
464*09467b48Spatrick   Value *Op = SI->getCondition();
465*09467b48Spatrick   if ((!isa<Instruction>(Op) && !isa<Argument>(Op)) || Op->hasOneUse())
466*09467b48Spatrick     return;
467*09467b48Spatrick 
468*09467b48Spatrick   // Remember how many outgoing edges there are to every successor.
469*09467b48Spatrick   SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
470*09467b48Spatrick   for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
471*09467b48Spatrick     BasicBlock *TargetBlock = SI->getSuccessor(i);
472*09467b48Spatrick     ++SwitchEdges[TargetBlock];
473*09467b48Spatrick   }
474*09467b48Spatrick 
475*09467b48Spatrick   // Now propagate info for each case value
476*09467b48Spatrick   for (auto C : SI->cases()) {
477*09467b48Spatrick     BasicBlock *TargetBlock = C.getCaseSuccessor();
478*09467b48Spatrick     if (SwitchEdges.lookup(TargetBlock) == 1) {
479*09467b48Spatrick       PredicateSwitch *PS = new PredicateSwitch(
480*09467b48Spatrick           Op, SI->getParent(), TargetBlock, C.getCaseValue(), SI);
481*09467b48Spatrick       addInfoFor(OpsToRename, Op, PS);
482*09467b48Spatrick       if (!TargetBlock->getSinglePredecessor())
483*09467b48Spatrick         EdgeUsesOnly.insert({BranchBB, TargetBlock});
484*09467b48Spatrick     }
485*09467b48Spatrick   }
486*09467b48Spatrick }
487*09467b48Spatrick 
488*09467b48Spatrick // Build predicate info for our function
489*09467b48Spatrick void PredicateInfo::buildPredicateInfo() {
490*09467b48Spatrick   DT.updateDFSNumbers();
491*09467b48Spatrick   // Collect operands to rename from all conditional branch terminators, as well
492*09467b48Spatrick   // as assume statements.
493*09467b48Spatrick   SmallVector<Value *, 8> OpsToRename;
494*09467b48Spatrick   for (auto DTN : depth_first(DT.getRootNode())) {
495*09467b48Spatrick     BasicBlock *BranchBB = DTN->getBlock();
496*09467b48Spatrick     if (auto *BI = dyn_cast<BranchInst>(BranchBB->getTerminator())) {
497*09467b48Spatrick       if (!BI->isConditional())
498*09467b48Spatrick         continue;
499*09467b48Spatrick       // Can't insert conditional information if they all go to the same place.
500*09467b48Spatrick       if (BI->getSuccessor(0) == BI->getSuccessor(1))
501*09467b48Spatrick         continue;
502*09467b48Spatrick       processBranch(BI, BranchBB, OpsToRename);
503*09467b48Spatrick     } else if (auto *SI = dyn_cast<SwitchInst>(BranchBB->getTerminator())) {
504*09467b48Spatrick       processSwitch(SI, BranchBB, OpsToRename);
505*09467b48Spatrick     }
506*09467b48Spatrick   }
507*09467b48Spatrick   for (auto &Assume : AC.assumptions()) {
508*09467b48Spatrick     if (auto *II = dyn_cast_or_null<IntrinsicInst>(Assume))
509*09467b48Spatrick       if (DT.isReachableFromEntry(II->getParent()))
510*09467b48Spatrick         processAssume(II, II->getParent(), OpsToRename);
511*09467b48Spatrick   }
512*09467b48Spatrick   // Now rename all our operations.
513*09467b48Spatrick   renameUses(OpsToRename);
514*09467b48Spatrick }
515*09467b48Spatrick 
516*09467b48Spatrick // Create a ssa_copy declaration with custom mangling, because
517*09467b48Spatrick // Intrinsic::getDeclaration does not handle overloaded unnamed types properly:
518*09467b48Spatrick // all unnamed types get mangled to the same string. We use the pointer
519*09467b48Spatrick // to the type as name here, as it guarantees unique names for different
520*09467b48Spatrick // types and we remove the declarations when destroying PredicateInfo.
521*09467b48Spatrick // It is a workaround for PR38117, because solving it in a fully general way is
522*09467b48Spatrick // tricky (FIXME).
523*09467b48Spatrick static Function *getCopyDeclaration(Module *M, Type *Ty) {
524*09467b48Spatrick   std::string Name = "llvm.ssa.copy." + utostr((uintptr_t) Ty);
525*09467b48Spatrick   return cast<Function>(
526*09467b48Spatrick       M->getOrInsertFunction(Name,
527*09467b48Spatrick                              getType(M->getContext(), Intrinsic::ssa_copy, Ty))
528*09467b48Spatrick           .getCallee());
529*09467b48Spatrick }
530*09467b48Spatrick 
531*09467b48Spatrick // Given the renaming stack, make all the operands currently on the stack real
532*09467b48Spatrick // by inserting them into the IR.  Return the last operation's value.
533*09467b48Spatrick Value *PredicateInfo::materializeStack(unsigned int &Counter,
534*09467b48Spatrick                                        ValueDFSStack &RenameStack,
535*09467b48Spatrick                                        Value *OrigOp) {
536*09467b48Spatrick   // Find the first thing we have to materialize
537*09467b48Spatrick   auto RevIter = RenameStack.rbegin();
538*09467b48Spatrick   for (; RevIter != RenameStack.rend(); ++RevIter)
539*09467b48Spatrick     if (RevIter->Def)
540*09467b48Spatrick       break;
541*09467b48Spatrick 
542*09467b48Spatrick   size_t Start = RevIter - RenameStack.rbegin();
543*09467b48Spatrick   // The maximum number of things we should be trying to materialize at once
544*09467b48Spatrick   // right now is 4, depending on if we had an assume, a branch, and both used
545*09467b48Spatrick   // and of conditions.
546*09467b48Spatrick   for (auto RenameIter = RenameStack.end() - Start;
547*09467b48Spatrick        RenameIter != RenameStack.end(); ++RenameIter) {
548*09467b48Spatrick     auto *Op =
549*09467b48Spatrick         RenameIter == RenameStack.begin() ? OrigOp : (RenameIter - 1)->Def;
550*09467b48Spatrick     ValueDFS &Result = *RenameIter;
551*09467b48Spatrick     auto *ValInfo = Result.PInfo;
552*09467b48Spatrick     // For edge predicates, we can just place the operand in the block before
553*09467b48Spatrick     // the terminator.  For assume, we have to place it right before the assume
554*09467b48Spatrick     // to ensure we dominate all of our uses.  Always insert right before the
555*09467b48Spatrick     // relevant instruction (terminator, assume), so that we insert in proper
556*09467b48Spatrick     // order in the case of multiple predicateinfo in the same block.
557*09467b48Spatrick     if (isa<PredicateWithEdge>(ValInfo)) {
558*09467b48Spatrick       IRBuilder<> B(getBranchTerminator(ValInfo));
559*09467b48Spatrick       Function *IF = getCopyDeclaration(F.getParent(), Op->getType());
560*09467b48Spatrick       if (IF->users().empty())
561*09467b48Spatrick         CreatedDeclarations.insert(IF);
562*09467b48Spatrick       CallInst *PIC =
563*09467b48Spatrick           B.CreateCall(IF, Op, Op->getName() + "." + Twine(Counter++));
564*09467b48Spatrick       PredicateMap.insert({PIC, ValInfo});
565*09467b48Spatrick       Result.Def = PIC;
566*09467b48Spatrick     } else {
567*09467b48Spatrick       auto *PAssume = dyn_cast<PredicateAssume>(ValInfo);
568*09467b48Spatrick       assert(PAssume &&
569*09467b48Spatrick              "Should not have gotten here without it being an assume");
570*09467b48Spatrick       IRBuilder<> B(PAssume->AssumeInst);
571*09467b48Spatrick       Function *IF = getCopyDeclaration(F.getParent(), Op->getType());
572*09467b48Spatrick       if (IF->users().empty())
573*09467b48Spatrick         CreatedDeclarations.insert(IF);
574*09467b48Spatrick       CallInst *PIC = B.CreateCall(IF, Op);
575*09467b48Spatrick       PredicateMap.insert({PIC, ValInfo});
576*09467b48Spatrick       Result.Def = PIC;
577*09467b48Spatrick     }
578*09467b48Spatrick   }
579*09467b48Spatrick   return RenameStack.back().Def;
580*09467b48Spatrick }
581*09467b48Spatrick 
582*09467b48Spatrick // Instead of the standard SSA renaming algorithm, which is O(Number of
583*09467b48Spatrick // instructions), and walks the entire dominator tree, we walk only the defs +
584*09467b48Spatrick // uses.  The standard SSA renaming algorithm does not really rely on the
585*09467b48Spatrick // dominator tree except to order the stack push/pops of the renaming stacks, so
586*09467b48Spatrick // that defs end up getting pushed before hitting the correct uses.  This does
587*09467b48Spatrick // not require the dominator tree, only the *order* of the dominator tree. The
588*09467b48Spatrick // complete and correct ordering of the defs and uses, in dominator tree is
589*09467b48Spatrick // contained in the DFS numbering of the dominator tree. So we sort the defs and
590*09467b48Spatrick // uses into the DFS ordering, and then just use the renaming stack as per
591*09467b48Spatrick // normal, pushing when we hit a def (which is a predicateinfo instruction),
592*09467b48Spatrick // popping when we are out of the dfs scope for that def, and replacing any uses
593*09467b48Spatrick // with top of stack if it exists.  In order to handle liveness without
594*09467b48Spatrick // propagating liveness info, we don't actually insert the predicateinfo
595*09467b48Spatrick // instruction def until we see a use that it would dominate.  Once we see such
596*09467b48Spatrick // a use, we materialize the predicateinfo instruction in the right place and
597*09467b48Spatrick // use it.
598*09467b48Spatrick //
599*09467b48Spatrick // TODO: Use this algorithm to perform fast single-variable renaming in
600*09467b48Spatrick // promotememtoreg and memoryssa.
601*09467b48Spatrick void PredicateInfo::renameUses(SmallVectorImpl<Value *> &OpsToRename) {
602*09467b48Spatrick   ValueDFS_Compare Compare(DT, OI);
603*09467b48Spatrick   // Compute liveness, and rename in O(uses) per Op.
604*09467b48Spatrick   for (auto *Op : OpsToRename) {
605*09467b48Spatrick     LLVM_DEBUG(dbgs() << "Visiting " << *Op << "\n");
606*09467b48Spatrick     unsigned Counter = 0;
607*09467b48Spatrick     SmallVector<ValueDFS, 16> OrderedUses;
608*09467b48Spatrick     const auto &ValueInfo = getValueInfo(Op);
609*09467b48Spatrick     // Insert the possible copies into the def/use list.
610*09467b48Spatrick     // They will become real copies if we find a real use for them, and never
611*09467b48Spatrick     // created otherwise.
612*09467b48Spatrick     for (auto &PossibleCopy : ValueInfo.Infos) {
613*09467b48Spatrick       ValueDFS VD;
614*09467b48Spatrick       // Determine where we are going to place the copy by the copy type.
615*09467b48Spatrick       // The predicate info for branches always come first, they will get
616*09467b48Spatrick       // materialized in the split block at the top of the block.
617*09467b48Spatrick       // The predicate info for assumes will be somewhere in the middle,
618*09467b48Spatrick       // it will get materialized in front of the assume.
619*09467b48Spatrick       if (const auto *PAssume = dyn_cast<PredicateAssume>(PossibleCopy)) {
620*09467b48Spatrick         VD.LocalNum = LN_Middle;
621*09467b48Spatrick         DomTreeNode *DomNode = DT.getNode(PAssume->AssumeInst->getParent());
622*09467b48Spatrick         if (!DomNode)
623*09467b48Spatrick           continue;
624*09467b48Spatrick         VD.DFSIn = DomNode->getDFSNumIn();
625*09467b48Spatrick         VD.DFSOut = DomNode->getDFSNumOut();
626*09467b48Spatrick         VD.PInfo = PossibleCopy;
627*09467b48Spatrick         OrderedUses.push_back(VD);
628*09467b48Spatrick       } else if (isa<PredicateWithEdge>(PossibleCopy)) {
629*09467b48Spatrick         // If we can only do phi uses, we treat it like it's in the branch
630*09467b48Spatrick         // block, and handle it specially. We know that it goes last, and only
631*09467b48Spatrick         // dominate phi uses.
632*09467b48Spatrick         auto BlockEdge = getBlockEdge(PossibleCopy);
633*09467b48Spatrick         if (EdgeUsesOnly.count(BlockEdge)) {
634*09467b48Spatrick           VD.LocalNum = LN_Last;
635*09467b48Spatrick           auto *DomNode = DT.getNode(BlockEdge.first);
636*09467b48Spatrick           if (DomNode) {
637*09467b48Spatrick             VD.DFSIn = DomNode->getDFSNumIn();
638*09467b48Spatrick             VD.DFSOut = DomNode->getDFSNumOut();
639*09467b48Spatrick             VD.PInfo = PossibleCopy;
640*09467b48Spatrick             VD.EdgeOnly = true;
641*09467b48Spatrick             OrderedUses.push_back(VD);
642*09467b48Spatrick           }
643*09467b48Spatrick         } else {
644*09467b48Spatrick           // Otherwise, we are in the split block (even though we perform
645*09467b48Spatrick           // insertion in the branch block).
646*09467b48Spatrick           // Insert a possible copy at the split block and before the branch.
647*09467b48Spatrick           VD.LocalNum = LN_First;
648*09467b48Spatrick           auto *DomNode = DT.getNode(BlockEdge.second);
649*09467b48Spatrick           if (DomNode) {
650*09467b48Spatrick             VD.DFSIn = DomNode->getDFSNumIn();
651*09467b48Spatrick             VD.DFSOut = DomNode->getDFSNumOut();
652*09467b48Spatrick             VD.PInfo = PossibleCopy;
653*09467b48Spatrick             OrderedUses.push_back(VD);
654*09467b48Spatrick           }
655*09467b48Spatrick         }
656*09467b48Spatrick       }
657*09467b48Spatrick     }
658*09467b48Spatrick 
659*09467b48Spatrick     convertUsesToDFSOrdered(Op, OrderedUses);
660*09467b48Spatrick     // Here we require a stable sort because we do not bother to try to
661*09467b48Spatrick     // assign an order to the operands the uses represent. Thus, two
662*09467b48Spatrick     // uses in the same instruction do not have a strict sort order
663*09467b48Spatrick     // currently and will be considered equal. We could get rid of the
664*09467b48Spatrick     // stable sort by creating one if we wanted.
665*09467b48Spatrick     llvm::stable_sort(OrderedUses, Compare);
666*09467b48Spatrick     SmallVector<ValueDFS, 8> RenameStack;
667*09467b48Spatrick     // For each use, sorted into dfs order, push values and replaces uses with
668*09467b48Spatrick     // top of stack, which will represent the reaching def.
669*09467b48Spatrick     for (auto &VD : OrderedUses) {
670*09467b48Spatrick       // We currently do not materialize copy over copy, but we should decide if
671*09467b48Spatrick       // we want to.
672*09467b48Spatrick       bool PossibleCopy = VD.PInfo != nullptr;
673*09467b48Spatrick       if (RenameStack.empty()) {
674*09467b48Spatrick         LLVM_DEBUG(dbgs() << "Rename Stack is empty\n");
675*09467b48Spatrick       } else {
676*09467b48Spatrick         LLVM_DEBUG(dbgs() << "Rename Stack Top DFS numbers are ("
677*09467b48Spatrick                           << RenameStack.back().DFSIn << ","
678*09467b48Spatrick                           << RenameStack.back().DFSOut << ")\n");
679*09467b48Spatrick       }
680*09467b48Spatrick 
681*09467b48Spatrick       LLVM_DEBUG(dbgs() << "Current DFS numbers are (" << VD.DFSIn << ","
682*09467b48Spatrick                         << VD.DFSOut << ")\n");
683*09467b48Spatrick 
684*09467b48Spatrick       bool ShouldPush = (VD.Def || PossibleCopy);
685*09467b48Spatrick       bool OutOfScope = !stackIsInScope(RenameStack, VD);
686*09467b48Spatrick       if (OutOfScope || ShouldPush) {
687*09467b48Spatrick         // Sync to our current scope.
688*09467b48Spatrick         popStackUntilDFSScope(RenameStack, VD);
689*09467b48Spatrick         if (ShouldPush) {
690*09467b48Spatrick           RenameStack.push_back(VD);
691*09467b48Spatrick         }
692*09467b48Spatrick       }
693*09467b48Spatrick       // If we get to this point, and the stack is empty we must have a use
694*09467b48Spatrick       // with no renaming needed, just skip it.
695*09467b48Spatrick       if (RenameStack.empty())
696*09467b48Spatrick         continue;
697*09467b48Spatrick       // Skip values, only want to rename the uses
698*09467b48Spatrick       if (VD.Def || PossibleCopy)
699*09467b48Spatrick         continue;
700*09467b48Spatrick       if (!DebugCounter::shouldExecute(RenameCounter)) {
701*09467b48Spatrick         LLVM_DEBUG(dbgs() << "Skipping execution due to debug counter\n");
702*09467b48Spatrick         continue;
703*09467b48Spatrick       }
704*09467b48Spatrick       ValueDFS &Result = RenameStack.back();
705*09467b48Spatrick 
706*09467b48Spatrick       // If the possible copy dominates something, materialize our stack up to
707*09467b48Spatrick       // this point. This ensures every comparison that affects our operation
708*09467b48Spatrick       // ends up with predicateinfo.
709*09467b48Spatrick       if (!Result.Def)
710*09467b48Spatrick         Result.Def = materializeStack(Counter, RenameStack, Op);
711*09467b48Spatrick 
712*09467b48Spatrick       LLVM_DEBUG(dbgs() << "Found replacement " << *Result.Def << " for "
713*09467b48Spatrick                         << *VD.U->get() << " in " << *(VD.U->getUser())
714*09467b48Spatrick                         << "\n");
715*09467b48Spatrick       assert(DT.dominates(cast<Instruction>(Result.Def), *VD.U) &&
716*09467b48Spatrick              "Predicateinfo def should have dominated this use");
717*09467b48Spatrick       VD.U->set(Result.Def);
718*09467b48Spatrick     }
719*09467b48Spatrick   }
720*09467b48Spatrick }
721*09467b48Spatrick 
722*09467b48Spatrick PredicateInfo::ValueInfo &PredicateInfo::getOrCreateValueInfo(Value *Operand) {
723*09467b48Spatrick   auto OIN = ValueInfoNums.find(Operand);
724*09467b48Spatrick   if (OIN == ValueInfoNums.end()) {
725*09467b48Spatrick     // This will grow it
726*09467b48Spatrick     ValueInfos.resize(ValueInfos.size() + 1);
727*09467b48Spatrick     // This will use the new size and give us a 0 based number of the info
728*09467b48Spatrick     auto InsertResult = ValueInfoNums.insert({Operand, ValueInfos.size() - 1});
729*09467b48Spatrick     assert(InsertResult.second && "Value info number already existed?");
730*09467b48Spatrick     return ValueInfos[InsertResult.first->second];
731*09467b48Spatrick   }
732*09467b48Spatrick   return ValueInfos[OIN->second];
733*09467b48Spatrick }
734*09467b48Spatrick 
735*09467b48Spatrick const PredicateInfo::ValueInfo &
736*09467b48Spatrick PredicateInfo::getValueInfo(Value *Operand) const {
737*09467b48Spatrick   auto OINI = ValueInfoNums.lookup(Operand);
738*09467b48Spatrick   assert(OINI != 0 && "Operand was not really in the Value Info Numbers");
739*09467b48Spatrick   assert(OINI < ValueInfos.size() &&
740*09467b48Spatrick          "Value Info Number greater than size of Value Info Table");
741*09467b48Spatrick   return ValueInfos[OINI];
742*09467b48Spatrick }
743*09467b48Spatrick 
744*09467b48Spatrick PredicateInfo::PredicateInfo(Function &F, DominatorTree &DT,
745*09467b48Spatrick                              AssumptionCache &AC)
746*09467b48Spatrick     : F(F), DT(DT), AC(AC), OI(&DT) {
747*09467b48Spatrick   // Push an empty operand info so that we can detect 0 as not finding one
748*09467b48Spatrick   ValueInfos.resize(1);
749*09467b48Spatrick   buildPredicateInfo();
750*09467b48Spatrick }
751*09467b48Spatrick 
752*09467b48Spatrick // Remove all declarations we created . The PredicateInfo consumers are
753*09467b48Spatrick // responsible for remove the ssa_copy calls created.
754*09467b48Spatrick PredicateInfo::~PredicateInfo() {
755*09467b48Spatrick   // Collect function pointers in set first, as SmallSet uses a SmallVector
756*09467b48Spatrick   // internally and we have to remove the asserting value handles first.
757*09467b48Spatrick   SmallPtrSet<Function *, 20> FunctionPtrs;
758*09467b48Spatrick   for (auto &F : CreatedDeclarations)
759*09467b48Spatrick     FunctionPtrs.insert(&*F);
760*09467b48Spatrick   CreatedDeclarations.clear();
761*09467b48Spatrick 
762*09467b48Spatrick   for (Function *F : FunctionPtrs) {
763*09467b48Spatrick     assert(F->user_begin() == F->user_end() &&
764*09467b48Spatrick            "PredicateInfo consumer did not remove all SSA copies.");
765*09467b48Spatrick     F->eraseFromParent();
766*09467b48Spatrick   }
767*09467b48Spatrick }
768*09467b48Spatrick 
769*09467b48Spatrick void PredicateInfo::verifyPredicateInfo() const {}
770*09467b48Spatrick 
771*09467b48Spatrick char PredicateInfoPrinterLegacyPass::ID = 0;
772*09467b48Spatrick 
773*09467b48Spatrick PredicateInfoPrinterLegacyPass::PredicateInfoPrinterLegacyPass()
774*09467b48Spatrick     : FunctionPass(ID) {
775*09467b48Spatrick   initializePredicateInfoPrinterLegacyPassPass(
776*09467b48Spatrick       *PassRegistry::getPassRegistry());
777*09467b48Spatrick }
778*09467b48Spatrick 
779*09467b48Spatrick void PredicateInfoPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
780*09467b48Spatrick   AU.setPreservesAll();
781*09467b48Spatrick   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
782*09467b48Spatrick   AU.addRequired<AssumptionCacheTracker>();
783*09467b48Spatrick }
784*09467b48Spatrick 
785*09467b48Spatrick // Replace ssa_copy calls created by PredicateInfo with their operand.
786*09467b48Spatrick static void replaceCreatedSSACopys(PredicateInfo &PredInfo, Function &F) {
787*09467b48Spatrick   for (auto I = inst_begin(F), E = inst_end(F); I != E;) {
788*09467b48Spatrick     Instruction *Inst = &*I++;
789*09467b48Spatrick     const auto *PI = PredInfo.getPredicateInfoFor(Inst);
790*09467b48Spatrick     auto *II = dyn_cast<IntrinsicInst>(Inst);
791*09467b48Spatrick     if (!PI || !II || II->getIntrinsicID() != Intrinsic::ssa_copy)
792*09467b48Spatrick       continue;
793*09467b48Spatrick 
794*09467b48Spatrick     Inst->replaceAllUsesWith(II->getOperand(0));
795*09467b48Spatrick     Inst->eraseFromParent();
796*09467b48Spatrick   }
797*09467b48Spatrick }
798*09467b48Spatrick 
799*09467b48Spatrick bool PredicateInfoPrinterLegacyPass::runOnFunction(Function &F) {
800*09467b48Spatrick   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
801*09467b48Spatrick   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
802*09467b48Spatrick   auto PredInfo = std::make_unique<PredicateInfo>(F, DT, AC);
803*09467b48Spatrick   PredInfo->print(dbgs());
804*09467b48Spatrick   if (VerifyPredicateInfo)
805*09467b48Spatrick     PredInfo->verifyPredicateInfo();
806*09467b48Spatrick 
807*09467b48Spatrick   replaceCreatedSSACopys(*PredInfo, F);
808*09467b48Spatrick   return false;
809*09467b48Spatrick }
810*09467b48Spatrick 
811*09467b48Spatrick PreservedAnalyses PredicateInfoPrinterPass::run(Function &F,
812*09467b48Spatrick                                                 FunctionAnalysisManager &AM) {
813*09467b48Spatrick   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
814*09467b48Spatrick   auto &AC = AM.getResult<AssumptionAnalysis>(F);
815*09467b48Spatrick   OS << "PredicateInfo for function: " << F.getName() << "\n";
816*09467b48Spatrick   auto PredInfo = std::make_unique<PredicateInfo>(F, DT, AC);
817*09467b48Spatrick   PredInfo->print(OS);
818*09467b48Spatrick 
819*09467b48Spatrick   replaceCreatedSSACopys(*PredInfo, F);
820*09467b48Spatrick   return PreservedAnalyses::all();
821*09467b48Spatrick }
822*09467b48Spatrick 
823*09467b48Spatrick /// An assembly annotator class to print PredicateInfo information in
824*09467b48Spatrick /// comments.
825*09467b48Spatrick class PredicateInfoAnnotatedWriter : public AssemblyAnnotationWriter {
826*09467b48Spatrick   friend class PredicateInfo;
827*09467b48Spatrick   const PredicateInfo *PredInfo;
828*09467b48Spatrick 
829*09467b48Spatrick public:
830*09467b48Spatrick   PredicateInfoAnnotatedWriter(const PredicateInfo *M) : PredInfo(M) {}
831*09467b48Spatrick 
832*09467b48Spatrick   virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
833*09467b48Spatrick                                         formatted_raw_ostream &OS) {}
834*09467b48Spatrick 
835*09467b48Spatrick   virtual void emitInstructionAnnot(const Instruction *I,
836*09467b48Spatrick                                     formatted_raw_ostream &OS) {
837*09467b48Spatrick     if (const auto *PI = PredInfo->getPredicateInfoFor(I)) {
838*09467b48Spatrick       OS << "; Has predicate info\n";
839*09467b48Spatrick       if (const auto *PB = dyn_cast<PredicateBranch>(PI)) {
840*09467b48Spatrick         OS << "; branch predicate info { TrueEdge: " << PB->TrueEdge
841*09467b48Spatrick            << " Comparison:" << *PB->Condition << " Edge: [";
842*09467b48Spatrick         PB->From->printAsOperand(OS);
843*09467b48Spatrick         OS << ",";
844*09467b48Spatrick         PB->To->printAsOperand(OS);
845*09467b48Spatrick         OS << "] }\n";
846*09467b48Spatrick       } else if (const auto *PS = dyn_cast<PredicateSwitch>(PI)) {
847*09467b48Spatrick         OS << "; switch predicate info { CaseValue: " << *PS->CaseValue
848*09467b48Spatrick            << " Switch:" << *PS->Switch << " Edge: [";
849*09467b48Spatrick         PS->From->printAsOperand(OS);
850*09467b48Spatrick         OS << ",";
851*09467b48Spatrick         PS->To->printAsOperand(OS);
852*09467b48Spatrick         OS << "] }\n";
853*09467b48Spatrick       } else if (const auto *PA = dyn_cast<PredicateAssume>(PI)) {
854*09467b48Spatrick         OS << "; assume predicate info {"
855*09467b48Spatrick            << " Comparison:" << *PA->Condition << " }\n";
856*09467b48Spatrick       }
857*09467b48Spatrick     }
858*09467b48Spatrick   }
859*09467b48Spatrick };
860*09467b48Spatrick 
861*09467b48Spatrick void PredicateInfo::print(raw_ostream &OS) const {
862*09467b48Spatrick   PredicateInfoAnnotatedWriter Writer(this);
863*09467b48Spatrick   F.print(OS, &Writer);
864*09467b48Spatrick }
865*09467b48Spatrick 
866*09467b48Spatrick void PredicateInfo::dump() const {
867*09467b48Spatrick   PredicateInfoAnnotatedWriter Writer(this);
868*09467b48Spatrick   F.print(dbgs(), &Writer);
869*09467b48Spatrick }
870*09467b48Spatrick 
871*09467b48Spatrick PreservedAnalyses PredicateInfoVerifierPass::run(Function &F,
872*09467b48Spatrick                                                  FunctionAnalysisManager &AM) {
873*09467b48Spatrick   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
874*09467b48Spatrick   auto &AC = AM.getResult<AssumptionAnalysis>(F);
875*09467b48Spatrick   std::make_unique<PredicateInfo>(F, DT, AC)->verifyPredicateInfo();
876*09467b48Spatrick 
877*09467b48Spatrick   return PreservedAnalyses::all();
878*09467b48Spatrick }
879*09467b48Spatrick }
880