xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp (revision fe6060f10f634930ff71b7c50291ddc610da2475)
1e8d8bef9SDimitry Andric //===-- ConstraintElimination.cpp - Eliminate conds using constraints. ----===//
2e8d8bef9SDimitry Andric //
3e8d8bef9SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e8d8bef9SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e8d8bef9SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e8d8bef9SDimitry Andric //
7e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
8e8d8bef9SDimitry Andric //
9e8d8bef9SDimitry Andric // Eliminate conditions based on constraints collected from dominating
10e8d8bef9SDimitry Andric // conditions.
11e8d8bef9SDimitry Andric //
12e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
13e8d8bef9SDimitry Andric 
14e8d8bef9SDimitry Andric #include "llvm/Transforms/Scalar/ConstraintElimination.h"
15e8d8bef9SDimitry Andric #include "llvm/ADT/STLExtras.h"
16*fe6060f1SDimitry Andric #include "llvm/ADT/ScopeExit.h"
17e8d8bef9SDimitry Andric #include "llvm/ADT/SmallVector.h"
18e8d8bef9SDimitry Andric #include "llvm/ADT/Statistic.h"
19e8d8bef9SDimitry Andric #include "llvm/Analysis/ConstraintSystem.h"
20e8d8bef9SDimitry Andric #include "llvm/Analysis/GlobalsModRef.h"
21e8d8bef9SDimitry Andric #include "llvm/IR/DataLayout.h"
22e8d8bef9SDimitry Andric #include "llvm/IR/Dominators.h"
23e8d8bef9SDimitry Andric #include "llvm/IR/Function.h"
24e8d8bef9SDimitry Andric #include "llvm/IR/Instructions.h"
25e8d8bef9SDimitry Andric #include "llvm/IR/PatternMatch.h"
26e8d8bef9SDimitry Andric #include "llvm/InitializePasses.h"
27e8d8bef9SDimitry Andric #include "llvm/Pass.h"
28e8d8bef9SDimitry Andric #include "llvm/Support/Debug.h"
29e8d8bef9SDimitry Andric #include "llvm/Support/DebugCounter.h"
30e8d8bef9SDimitry Andric #include "llvm/Transforms/Scalar.h"
31e8d8bef9SDimitry Andric 
32*fe6060f1SDimitry Andric #include <string>
33*fe6060f1SDimitry Andric 
34e8d8bef9SDimitry Andric using namespace llvm;
35e8d8bef9SDimitry Andric using namespace PatternMatch;
36e8d8bef9SDimitry Andric 
37e8d8bef9SDimitry Andric #define DEBUG_TYPE "constraint-elimination"
38e8d8bef9SDimitry Andric 
39e8d8bef9SDimitry Andric STATISTIC(NumCondsRemoved, "Number of instructions removed");
40e8d8bef9SDimitry Andric DEBUG_COUNTER(EliminatedCounter, "conds-eliminated",
41e8d8bef9SDimitry Andric               "Controls which conditions are eliminated");
42e8d8bef9SDimitry Andric 
43e8d8bef9SDimitry Andric static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max();
44e8d8bef9SDimitry Andric 
45e8d8bef9SDimitry Andric // Decomposes \p V into a vector of pairs of the form { c, X } where c * X. The
46e8d8bef9SDimitry Andric // sum of the pairs equals \p V.  The first pair is the constant-factor and X
47e8d8bef9SDimitry Andric // must be nullptr. If the expression cannot be decomposed, returns an empty
48e8d8bef9SDimitry Andric // vector.
49e8d8bef9SDimitry Andric static SmallVector<std::pair<int64_t, Value *>, 4> decompose(Value *V) {
50e8d8bef9SDimitry Andric   if (auto *CI = dyn_cast<ConstantInt>(V)) {
51e8d8bef9SDimitry Andric     if (CI->isNegative() || CI->uge(MaxConstraintValue))
52e8d8bef9SDimitry Andric       return {};
53e8d8bef9SDimitry Andric     return {{CI->getSExtValue(), nullptr}};
54e8d8bef9SDimitry Andric   }
55e8d8bef9SDimitry Andric   auto *GEP = dyn_cast<GetElementPtrInst>(V);
56*fe6060f1SDimitry Andric   if (GEP && GEP->getNumOperands() == 2 && GEP->isInBounds()) {
57*fe6060f1SDimitry Andric     Value *Op0, *Op1;
58e8d8bef9SDimitry Andric     ConstantInt *CI;
59*fe6060f1SDimitry Andric 
60*fe6060f1SDimitry Andric     // If the index is zero-extended, it is guaranteed to be positive.
61*fe6060f1SDimitry Andric     if (match(GEP->getOperand(GEP->getNumOperands() - 1),
62*fe6060f1SDimitry Andric               m_ZExt(m_Value(Op0)))) {
63*fe6060f1SDimitry Andric       if (match(Op0, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))))
64*fe6060f1SDimitry Andric         return {{0, nullptr},
65*fe6060f1SDimitry Andric                 {1, GEP->getPointerOperand()},
66*fe6060f1SDimitry Andric                 {std::pow(int64_t(2), CI->getSExtValue()), Op1}};
67*fe6060f1SDimitry Andric       if (match(Op0, m_NSWAdd(m_Value(Op1), m_ConstantInt(CI))))
68*fe6060f1SDimitry Andric         return {{CI->getSExtValue(), nullptr},
69*fe6060f1SDimitry Andric                 {1, GEP->getPointerOperand()},
70*fe6060f1SDimitry Andric                 {1, Op1}};
71*fe6060f1SDimitry Andric       return {{0, nullptr}, {1, GEP->getPointerOperand()}, {1, Op0}};
72*fe6060f1SDimitry Andric     }
73*fe6060f1SDimitry Andric 
74*fe6060f1SDimitry Andric     if (match(GEP->getOperand(GEP->getNumOperands() - 1), m_ConstantInt(CI)) &&
75*fe6060f1SDimitry Andric         !CI->isNegative())
76*fe6060f1SDimitry Andric       return {{CI->getSExtValue(), nullptr}, {1, GEP->getPointerOperand()}};
77*fe6060f1SDimitry Andric 
78*fe6060f1SDimitry Andric     SmallVector<std::pair<int64_t, Value *>, 4> Result;
79e8d8bef9SDimitry Andric     if (match(GEP->getOperand(GEP->getNumOperands() - 1),
80e8d8bef9SDimitry Andric               m_NUWShl(m_Value(Op0), m_ConstantInt(CI))))
81*fe6060f1SDimitry Andric       Result = {{0, nullptr},
82e8d8bef9SDimitry Andric                 {1, GEP->getPointerOperand()},
83e8d8bef9SDimitry Andric                 {std::pow(int64_t(2), CI->getSExtValue()), Op0}};
84*fe6060f1SDimitry Andric     else if (match(GEP->getOperand(GEP->getNumOperands() - 1),
85*fe6060f1SDimitry Andric                    m_NSWAdd(m_Value(Op0), m_ConstantInt(CI))))
86*fe6060f1SDimitry Andric       Result = {{CI->getSExtValue(), nullptr},
87e8d8bef9SDimitry Andric                 {1, GEP->getPointerOperand()},
88*fe6060f1SDimitry Andric                 {1, Op0}};
89*fe6060f1SDimitry Andric     else {
90*fe6060f1SDimitry Andric       Op0 = GEP->getOperand(GEP->getNumOperands() - 1);
91*fe6060f1SDimitry Andric       Result = {{0, nullptr}, {1, GEP->getPointerOperand()}, {1, Op0}};
92*fe6060f1SDimitry Andric     }
93*fe6060f1SDimitry Andric     return Result;
94e8d8bef9SDimitry Andric   }
95e8d8bef9SDimitry Andric 
96e8d8bef9SDimitry Andric   Value *Op0;
97*fe6060f1SDimitry Andric   if (match(V, m_ZExt(m_Value(Op0))))
98*fe6060f1SDimitry Andric     V = Op0;
99*fe6060f1SDimitry Andric 
100e8d8bef9SDimitry Andric   Value *Op1;
101e8d8bef9SDimitry Andric   ConstantInt *CI;
102e8d8bef9SDimitry Andric   if (match(V, m_NUWAdd(m_Value(Op0), m_ConstantInt(CI))))
103e8d8bef9SDimitry Andric     return {{CI->getSExtValue(), nullptr}, {1, Op0}};
104e8d8bef9SDimitry Andric   if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1))))
105e8d8bef9SDimitry Andric     return {{0, nullptr}, {1, Op0}, {1, Op1}};
106e8d8bef9SDimitry Andric 
107e8d8bef9SDimitry Andric   if (match(V, m_NUWSub(m_Value(Op0), m_ConstantInt(CI))))
108e8d8bef9SDimitry Andric     return {{-1 * CI->getSExtValue(), nullptr}, {1, Op0}};
109e8d8bef9SDimitry Andric   if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1))))
110e8d8bef9SDimitry Andric     return {{0, nullptr}, {1, Op0}, {1, Op1}};
111e8d8bef9SDimitry Andric 
112e8d8bef9SDimitry Andric   return {{0, nullptr}, {1, V}};
113e8d8bef9SDimitry Andric }
114e8d8bef9SDimitry Andric 
115*fe6060f1SDimitry Andric struct ConstraintTy {
116*fe6060f1SDimitry Andric   SmallVector<int64_t, 8> Coefficients;
117*fe6060f1SDimitry Andric 
118*fe6060f1SDimitry Andric   ConstraintTy(SmallVector<int64_t, 8> Coefficients)
119*fe6060f1SDimitry Andric       : Coefficients(Coefficients) {}
120*fe6060f1SDimitry Andric 
121*fe6060f1SDimitry Andric   unsigned size() const { return Coefficients.size(); }
122*fe6060f1SDimitry Andric };
123*fe6060f1SDimitry Andric 
124*fe6060f1SDimitry Andric /// Turn a condition \p CmpI into a vector of constraints, using indices from \p
125*fe6060f1SDimitry Andric /// Value2Index. Additional indices for newly discovered values are added to \p
126*fe6060f1SDimitry Andric /// NewIndices.
127*fe6060f1SDimitry Andric static SmallVector<ConstraintTy, 4>
128e8d8bef9SDimitry Andric getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1,
129*fe6060f1SDimitry Andric               const DenseMap<Value *, unsigned> &Value2Index,
130*fe6060f1SDimitry Andric               DenseMap<Value *, unsigned> &NewIndices) {
131e8d8bef9SDimitry Andric   int64_t Offset1 = 0;
132e8d8bef9SDimitry Andric   int64_t Offset2 = 0;
133e8d8bef9SDimitry Andric 
134*fe6060f1SDimitry Andric   // First try to look up \p V in Value2Index and NewIndices. Otherwise add a
135*fe6060f1SDimitry Andric   // new entry to NewIndices.
136*fe6060f1SDimitry Andric   auto GetOrAddIndex = [&Value2Index, &NewIndices](Value *V) -> unsigned {
137*fe6060f1SDimitry Andric     auto V2I = Value2Index.find(V);
138*fe6060f1SDimitry Andric     if (V2I != Value2Index.end())
139*fe6060f1SDimitry Andric       return V2I->second;
140*fe6060f1SDimitry Andric     auto NewI = NewIndices.find(V);
141*fe6060f1SDimitry Andric     if (NewI != NewIndices.end())
142*fe6060f1SDimitry Andric       return NewI->second;
143*fe6060f1SDimitry Andric     auto Insert =
144*fe6060f1SDimitry Andric         NewIndices.insert({V, Value2Index.size() + NewIndices.size() + 1});
145*fe6060f1SDimitry Andric     return Insert.first->second;
146e8d8bef9SDimitry Andric   };
147e8d8bef9SDimitry Andric 
148e8d8bef9SDimitry Andric   if (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_UGE)
149e8d8bef9SDimitry Andric     return getConstraint(CmpInst::getSwappedPredicate(Pred), Op1, Op0,
150*fe6060f1SDimitry Andric                          Value2Index, NewIndices);
151*fe6060f1SDimitry Andric 
152*fe6060f1SDimitry Andric   if (Pred == CmpInst::ICMP_EQ) {
153*fe6060f1SDimitry Andric     auto A =
154*fe6060f1SDimitry Andric         getConstraint(CmpInst::ICMP_UGE, Op0, Op1, Value2Index, NewIndices);
155*fe6060f1SDimitry Andric     auto B =
156*fe6060f1SDimitry Andric         getConstraint(CmpInst::ICMP_ULE, Op0, Op1, Value2Index, NewIndices);
157*fe6060f1SDimitry Andric     append_range(A, B);
158*fe6060f1SDimitry Andric     return A;
159*fe6060f1SDimitry Andric   }
160*fe6060f1SDimitry Andric 
161*fe6060f1SDimitry Andric   if (Pred == CmpInst::ICMP_NE && match(Op1, m_Zero())) {
162*fe6060f1SDimitry Andric     return getConstraint(CmpInst::ICMP_UGT, Op0, Op1, Value2Index, NewIndices);
163*fe6060f1SDimitry Andric   }
164e8d8bef9SDimitry Andric 
165e8d8bef9SDimitry Andric   // Only ULE and ULT predicates are supported at the moment.
166e8d8bef9SDimitry Andric   if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT)
167e8d8bef9SDimitry Andric     return {};
168e8d8bef9SDimitry Andric 
169*fe6060f1SDimitry Andric   auto ADec = decompose(Op0->stripPointerCastsSameRepresentation());
170*fe6060f1SDimitry Andric   auto BDec = decompose(Op1->stripPointerCastsSameRepresentation());
171e8d8bef9SDimitry Andric   // Skip if decomposing either of the values failed.
172e8d8bef9SDimitry Andric   if (ADec.empty() || BDec.empty())
173e8d8bef9SDimitry Andric     return {};
174e8d8bef9SDimitry Andric 
175e8d8bef9SDimitry Andric   // Skip trivial constraints without any variables.
176e8d8bef9SDimitry Andric   if (ADec.size() == 1 && BDec.size() == 1)
177e8d8bef9SDimitry Andric     return {};
178e8d8bef9SDimitry Andric 
179e8d8bef9SDimitry Andric   Offset1 = ADec[0].first;
180e8d8bef9SDimitry Andric   Offset2 = BDec[0].first;
181e8d8bef9SDimitry Andric   Offset1 *= -1;
182e8d8bef9SDimitry Andric 
183e8d8bef9SDimitry Andric   // Create iterator ranges that skip the constant-factor.
184*fe6060f1SDimitry Andric   auto VariablesA = llvm::drop_begin(ADec);
185*fe6060f1SDimitry Andric   auto VariablesB = llvm::drop_begin(BDec);
186e8d8bef9SDimitry Andric 
187*fe6060f1SDimitry Andric   // Make sure all variables have entries in Value2Index or NewIndices.
188e8d8bef9SDimitry Andric   for (const auto &KV :
189e8d8bef9SDimitry Andric        concat<std::pair<int64_t, Value *>>(VariablesA, VariablesB))
190*fe6060f1SDimitry Andric     GetOrAddIndex(KV.second);
191e8d8bef9SDimitry Andric 
192e8d8bef9SDimitry Andric   // Build result constraint, by first adding all coefficients from A and then
193e8d8bef9SDimitry Andric   // subtracting all coefficients from B.
194*fe6060f1SDimitry Andric   SmallVector<int64_t, 8> R(Value2Index.size() + NewIndices.size() + 1, 0);
195e8d8bef9SDimitry Andric   for (const auto &KV : VariablesA)
196*fe6060f1SDimitry Andric     R[GetOrAddIndex(KV.second)] += KV.first;
197e8d8bef9SDimitry Andric 
198e8d8bef9SDimitry Andric   for (const auto &KV : VariablesB)
199*fe6060f1SDimitry Andric     R[GetOrAddIndex(KV.second)] -= KV.first;
200e8d8bef9SDimitry Andric 
201e8d8bef9SDimitry Andric   R[0] = Offset1 + Offset2 + (Pred == CmpInst::ICMP_ULT ? -1 : 0);
202*fe6060f1SDimitry Andric   return {R};
203e8d8bef9SDimitry Andric }
204e8d8bef9SDimitry Andric 
205*fe6060f1SDimitry Andric static SmallVector<ConstraintTy, 4>
206*fe6060f1SDimitry Andric getConstraint(CmpInst *Cmp, const DenseMap<Value *, unsigned> &Value2Index,
207*fe6060f1SDimitry Andric               DenseMap<Value *, unsigned> &NewIndices) {
208e8d8bef9SDimitry Andric   return getConstraint(Cmp->getPredicate(), Cmp->getOperand(0),
209*fe6060f1SDimitry Andric                        Cmp->getOperand(1), Value2Index, NewIndices);
210e8d8bef9SDimitry Andric }
211e8d8bef9SDimitry Andric 
212e8d8bef9SDimitry Andric namespace {
213e8d8bef9SDimitry Andric /// Represents either a condition that holds on entry to a block or a basic
214e8d8bef9SDimitry Andric /// block, with their respective Dominator DFS in and out numbers.
215e8d8bef9SDimitry Andric struct ConstraintOrBlock {
216e8d8bef9SDimitry Andric   unsigned NumIn;
217e8d8bef9SDimitry Andric   unsigned NumOut;
218e8d8bef9SDimitry Andric   bool IsBlock;
219e8d8bef9SDimitry Andric   bool Not;
220e8d8bef9SDimitry Andric   union {
221e8d8bef9SDimitry Andric     BasicBlock *BB;
222e8d8bef9SDimitry Andric     CmpInst *Condition;
223e8d8bef9SDimitry Andric   };
224e8d8bef9SDimitry Andric 
225e8d8bef9SDimitry Andric   ConstraintOrBlock(DomTreeNode *DTN)
226e8d8bef9SDimitry Andric       : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(true),
227e8d8bef9SDimitry Andric         BB(DTN->getBlock()) {}
228e8d8bef9SDimitry Andric   ConstraintOrBlock(DomTreeNode *DTN, CmpInst *Condition, bool Not)
229e8d8bef9SDimitry Andric       : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(false),
230e8d8bef9SDimitry Andric         Not(Not), Condition(Condition) {}
231e8d8bef9SDimitry Andric };
232e8d8bef9SDimitry Andric 
233e8d8bef9SDimitry Andric struct StackEntry {
234e8d8bef9SDimitry Andric   unsigned NumIn;
235e8d8bef9SDimitry Andric   unsigned NumOut;
236e8d8bef9SDimitry Andric   CmpInst *Condition;
237e8d8bef9SDimitry Andric   bool IsNot;
238e8d8bef9SDimitry Andric 
239e8d8bef9SDimitry Andric   StackEntry(unsigned NumIn, unsigned NumOut, CmpInst *Condition, bool IsNot)
240e8d8bef9SDimitry Andric       : NumIn(NumIn), NumOut(NumOut), Condition(Condition), IsNot(IsNot) {}
241e8d8bef9SDimitry Andric };
242e8d8bef9SDimitry Andric } // namespace
243e8d8bef9SDimitry Andric 
244*fe6060f1SDimitry Andric #ifndef NDEBUG
245*fe6060f1SDimitry Andric static void dumpWithNames(ConstraintTy &C,
246*fe6060f1SDimitry Andric                           DenseMap<Value *, unsigned> &Value2Index) {
247*fe6060f1SDimitry Andric   SmallVector<std::string> Names(Value2Index.size(), "");
248*fe6060f1SDimitry Andric   for (auto &KV : Value2Index) {
249*fe6060f1SDimitry Andric     Names[KV.second - 1] = std::string("%") + KV.first->getName().str();
250*fe6060f1SDimitry Andric   }
251*fe6060f1SDimitry Andric   ConstraintSystem CS;
252*fe6060f1SDimitry Andric   CS.addVariableRowFill(C.Coefficients);
253*fe6060f1SDimitry Andric   CS.dump(Names);
254*fe6060f1SDimitry Andric }
255*fe6060f1SDimitry Andric #endif
256*fe6060f1SDimitry Andric 
257e8d8bef9SDimitry Andric static bool eliminateConstraints(Function &F, DominatorTree &DT) {
258e8d8bef9SDimitry Andric   bool Changed = false;
259e8d8bef9SDimitry Andric   DT.updateDFSNumbers();
260e8d8bef9SDimitry Andric   ConstraintSystem CS;
261e8d8bef9SDimitry Andric 
262e8d8bef9SDimitry Andric   SmallVector<ConstraintOrBlock, 64> WorkList;
263e8d8bef9SDimitry Andric 
264e8d8bef9SDimitry Andric   // First, collect conditions implied by branches and blocks with their
265e8d8bef9SDimitry Andric   // Dominator DFS in and out numbers.
266e8d8bef9SDimitry Andric   for (BasicBlock &BB : F) {
267e8d8bef9SDimitry Andric     if (!DT.getNode(&BB))
268e8d8bef9SDimitry Andric       continue;
269e8d8bef9SDimitry Andric     WorkList.emplace_back(DT.getNode(&BB));
270e8d8bef9SDimitry Andric 
271e8d8bef9SDimitry Andric     auto *Br = dyn_cast<BranchInst>(BB.getTerminator());
272e8d8bef9SDimitry Andric     if (!Br || !Br->isConditional())
273e8d8bef9SDimitry Andric       continue;
274e8d8bef9SDimitry Andric 
275*fe6060f1SDimitry Andric     // Returns true if we can add a known condition from BB to its successor
276*fe6060f1SDimitry Andric     // block Succ. Each predecessor of Succ can either be BB or be dominated by
277*fe6060f1SDimitry Andric     // Succ (e.g. the case when adding a condition from a pre-header to a loop
278*fe6060f1SDimitry Andric     // header).
279*fe6060f1SDimitry Andric     auto CanAdd = [&BB, &DT](BasicBlock *Succ) {
280*fe6060f1SDimitry Andric       return all_of(predecessors(Succ), [&BB, &DT, Succ](BasicBlock *Pred) {
281*fe6060f1SDimitry Andric         return Pred == &BB || DT.dominates(Succ, Pred);
282*fe6060f1SDimitry Andric       });
283*fe6060f1SDimitry Andric     };
284e8d8bef9SDimitry Andric     // If the condition is an OR of 2 compares and the false successor only has
285e8d8bef9SDimitry Andric     // the current block as predecessor, queue both negated conditions for the
286e8d8bef9SDimitry Andric     // false successor.
287e8d8bef9SDimitry Andric     Value *Op0, *Op1;
288e8d8bef9SDimitry Andric     if (match(Br->getCondition(), m_LogicalOr(m_Value(Op0), m_Value(Op1))) &&
289e8d8bef9SDimitry Andric         match(Op0, m_Cmp()) && match(Op1, m_Cmp())) {
290e8d8bef9SDimitry Andric       BasicBlock *FalseSuccessor = Br->getSuccessor(1);
291*fe6060f1SDimitry Andric       if (CanAdd(FalseSuccessor)) {
292e8d8bef9SDimitry Andric         WorkList.emplace_back(DT.getNode(FalseSuccessor), cast<CmpInst>(Op0),
293e8d8bef9SDimitry Andric                               true);
294e8d8bef9SDimitry Andric         WorkList.emplace_back(DT.getNode(FalseSuccessor), cast<CmpInst>(Op1),
295e8d8bef9SDimitry Andric                               true);
296e8d8bef9SDimitry Andric       }
297e8d8bef9SDimitry Andric       continue;
298e8d8bef9SDimitry Andric     }
299e8d8bef9SDimitry Andric 
300e8d8bef9SDimitry Andric     // If the condition is an AND of 2 compares and the true successor only has
301e8d8bef9SDimitry Andric     // the current block as predecessor, queue both conditions for the true
302e8d8bef9SDimitry Andric     // successor.
303e8d8bef9SDimitry Andric     if (match(Br->getCondition(), m_LogicalAnd(m_Value(Op0), m_Value(Op1))) &&
304e8d8bef9SDimitry Andric         match(Op0, m_Cmp()) && match(Op1, m_Cmp())) {
305e8d8bef9SDimitry Andric       BasicBlock *TrueSuccessor = Br->getSuccessor(0);
306*fe6060f1SDimitry Andric       if (CanAdd(TrueSuccessor)) {
307e8d8bef9SDimitry Andric         WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<CmpInst>(Op0),
308e8d8bef9SDimitry Andric                               false);
309e8d8bef9SDimitry Andric         WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<CmpInst>(Op1),
310e8d8bef9SDimitry Andric                               false);
311e8d8bef9SDimitry Andric       }
312e8d8bef9SDimitry Andric       continue;
313e8d8bef9SDimitry Andric     }
314e8d8bef9SDimitry Andric 
315e8d8bef9SDimitry Andric     auto *CmpI = dyn_cast<CmpInst>(Br->getCondition());
316e8d8bef9SDimitry Andric     if (!CmpI)
317e8d8bef9SDimitry Andric       continue;
318*fe6060f1SDimitry Andric     if (CanAdd(Br->getSuccessor(0)))
319e8d8bef9SDimitry Andric       WorkList.emplace_back(DT.getNode(Br->getSuccessor(0)), CmpI, false);
320*fe6060f1SDimitry Andric     if (CanAdd(Br->getSuccessor(1)))
321e8d8bef9SDimitry Andric       WorkList.emplace_back(DT.getNode(Br->getSuccessor(1)), CmpI, true);
322e8d8bef9SDimitry Andric   }
323e8d8bef9SDimitry Andric 
324e8d8bef9SDimitry Andric   // Next, sort worklist by dominance, so that dominating blocks and conditions
325e8d8bef9SDimitry Andric   // come before blocks and conditions dominated by them. If a block and a
326e8d8bef9SDimitry Andric   // condition have the same numbers, the condition comes before the block, as
327e8d8bef9SDimitry Andric   // it holds on entry to the block.
328e8d8bef9SDimitry Andric   sort(WorkList, [](const ConstraintOrBlock &A, const ConstraintOrBlock &B) {
329e8d8bef9SDimitry Andric     return std::tie(A.NumIn, A.IsBlock) < std::tie(B.NumIn, B.IsBlock);
330e8d8bef9SDimitry Andric   });
331e8d8bef9SDimitry Andric 
332e8d8bef9SDimitry Andric   // Finally, process ordered worklist and eliminate implied conditions.
333e8d8bef9SDimitry Andric   SmallVector<StackEntry, 16> DFSInStack;
334e8d8bef9SDimitry Andric   DenseMap<Value *, unsigned> Value2Index;
335e8d8bef9SDimitry Andric   for (ConstraintOrBlock &CB : WorkList) {
336e8d8bef9SDimitry Andric     // First, pop entries from the stack that are out-of-scope for CB. Remove
337e8d8bef9SDimitry Andric     // the corresponding entry from the constraint system.
338e8d8bef9SDimitry Andric     while (!DFSInStack.empty()) {
339e8d8bef9SDimitry Andric       auto &E = DFSInStack.back();
340e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut
341e8d8bef9SDimitry Andric                         << "\n");
342e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n");
343e8d8bef9SDimitry Andric       assert(E.NumIn <= CB.NumIn);
344e8d8bef9SDimitry Andric       if (CB.NumOut <= E.NumOut)
345e8d8bef9SDimitry Andric         break;
346e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Removing " << *E.Condition << " " << E.IsNot
347e8d8bef9SDimitry Andric                         << "\n");
348e8d8bef9SDimitry Andric       DFSInStack.pop_back();
349e8d8bef9SDimitry Andric       CS.popLastConstraint();
350e8d8bef9SDimitry Andric     }
351e8d8bef9SDimitry Andric 
352e8d8bef9SDimitry Andric     LLVM_DEBUG({
353e8d8bef9SDimitry Andric       dbgs() << "Processing ";
354e8d8bef9SDimitry Andric       if (CB.IsBlock)
355e8d8bef9SDimitry Andric         dbgs() << *CB.BB;
356e8d8bef9SDimitry Andric       else
357e8d8bef9SDimitry Andric         dbgs() << *CB.Condition;
358e8d8bef9SDimitry Andric       dbgs() << "\n";
359e8d8bef9SDimitry Andric     });
360e8d8bef9SDimitry Andric 
361e8d8bef9SDimitry Andric     // For a block, check if any CmpInsts become known based on the current set
362e8d8bef9SDimitry Andric     // of constraints.
363e8d8bef9SDimitry Andric     if (CB.IsBlock) {
364e8d8bef9SDimitry Andric       for (Instruction &I : *CB.BB) {
365e8d8bef9SDimitry Andric         auto *Cmp = dyn_cast<CmpInst>(&I);
366e8d8bef9SDimitry Andric         if (!Cmp)
367e8d8bef9SDimitry Andric           continue;
368*fe6060f1SDimitry Andric 
369*fe6060f1SDimitry Andric         DenseMap<Value *, unsigned> NewIndices;
370*fe6060f1SDimitry Andric         auto R = getConstraint(Cmp, Value2Index, NewIndices);
371*fe6060f1SDimitry Andric         if (R.size() != 1)
372e8d8bef9SDimitry Andric           continue;
373*fe6060f1SDimitry Andric 
374*fe6060f1SDimitry Andric         // Check if all coefficients of new indices are 0 after building the
375*fe6060f1SDimitry Andric         // constraint. Skip if any of the new indices has a non-null
376*fe6060f1SDimitry Andric         // coefficient.
377*fe6060f1SDimitry Andric         bool HasNewIndex = false;
378*fe6060f1SDimitry Andric         for (unsigned I = 0; I < NewIndices.size(); ++I) {
379*fe6060f1SDimitry Andric           int64_t Last = R[0].Coefficients.pop_back_val();
380*fe6060f1SDimitry Andric           if (Last != 0) {
381*fe6060f1SDimitry Andric             HasNewIndex = true;
382*fe6060f1SDimitry Andric             break;
383*fe6060f1SDimitry Andric           }
384*fe6060f1SDimitry Andric         }
385*fe6060f1SDimitry Andric         if (HasNewIndex || R[0].size() == 1)
386*fe6060f1SDimitry Andric           continue;
387*fe6060f1SDimitry Andric 
388*fe6060f1SDimitry Andric         if (CS.isConditionImplied(R[0].Coefficients)) {
389e8d8bef9SDimitry Andric           if (!DebugCounter::shouldExecute(EliminatedCounter))
390e8d8bef9SDimitry Andric             continue;
391e8d8bef9SDimitry Andric 
392e8d8bef9SDimitry Andric           LLVM_DEBUG(dbgs() << "Condition " << *Cmp
393e8d8bef9SDimitry Andric                             << " implied by dominating constraints\n");
394e8d8bef9SDimitry Andric           LLVM_DEBUG({
395e8d8bef9SDimitry Andric             for (auto &E : reverse(DFSInStack))
396e8d8bef9SDimitry Andric               dbgs() << "   C " << *E.Condition << " " << E.IsNot << "\n";
397e8d8bef9SDimitry Andric           });
398e8d8bef9SDimitry Andric           Cmp->replaceAllUsesWith(
399e8d8bef9SDimitry Andric               ConstantInt::getTrue(F.getParent()->getContext()));
400e8d8bef9SDimitry Andric           NumCondsRemoved++;
401e8d8bef9SDimitry Andric           Changed = true;
402e8d8bef9SDimitry Andric         }
403*fe6060f1SDimitry Andric         if (CS.isConditionImplied(
404*fe6060f1SDimitry Andric                 ConstraintSystem::negate(R[0].Coefficients))) {
405e8d8bef9SDimitry Andric           if (!DebugCounter::shouldExecute(EliminatedCounter))
406e8d8bef9SDimitry Andric             continue;
407e8d8bef9SDimitry Andric 
408e8d8bef9SDimitry Andric           LLVM_DEBUG(dbgs() << "Condition !" << *Cmp
409e8d8bef9SDimitry Andric                             << " implied by dominating constraints\n");
410e8d8bef9SDimitry Andric           LLVM_DEBUG({
411e8d8bef9SDimitry Andric             for (auto &E : reverse(DFSInStack))
412e8d8bef9SDimitry Andric               dbgs() << "   C " << *E.Condition << " " << E.IsNot << "\n";
413e8d8bef9SDimitry Andric           });
414e8d8bef9SDimitry Andric           Cmp->replaceAllUsesWith(
415e8d8bef9SDimitry Andric               ConstantInt::getFalse(F.getParent()->getContext()));
416e8d8bef9SDimitry Andric           NumCondsRemoved++;
417e8d8bef9SDimitry Andric           Changed = true;
418e8d8bef9SDimitry Andric         }
419e8d8bef9SDimitry Andric       }
420e8d8bef9SDimitry Andric       continue;
421e8d8bef9SDimitry Andric     }
422e8d8bef9SDimitry Andric 
423*fe6060f1SDimitry Andric     // Set up a function to restore the predicate at the end of the scope if it
424*fe6060f1SDimitry Andric     // has been negated. Negate the predicate in-place, if required.
425*fe6060f1SDimitry Andric     auto *CI = dyn_cast<CmpInst>(CB.Condition);
426*fe6060f1SDimitry Andric     auto PredicateRestorer = make_scope_exit([CI, &CB]() {
427*fe6060f1SDimitry Andric       if (CB.Not && CI)
428*fe6060f1SDimitry Andric         CI->setPredicate(CI->getInversePredicate());
429*fe6060f1SDimitry Andric     });
430*fe6060f1SDimitry Andric     if (CB.Not) {
431*fe6060f1SDimitry Andric       if (CI) {
432*fe6060f1SDimitry Andric         CI->setPredicate(CI->getInversePredicate());
433*fe6060f1SDimitry Andric       } else {
434*fe6060f1SDimitry Andric         LLVM_DEBUG(dbgs() << "Can only negate compares so far.\n");
435*fe6060f1SDimitry Andric         continue;
436*fe6060f1SDimitry Andric       }
437*fe6060f1SDimitry Andric     }
438*fe6060f1SDimitry Andric 
439e8d8bef9SDimitry Andric     // Otherwise, add the condition to the system and stack, if we can transform
440e8d8bef9SDimitry Andric     // it into a constraint.
441*fe6060f1SDimitry Andric     DenseMap<Value *, unsigned> NewIndices;
442*fe6060f1SDimitry Andric     auto R = getConstraint(CB.Condition, Value2Index, NewIndices);
443e8d8bef9SDimitry Andric     if (R.empty())
444e8d8bef9SDimitry Andric       continue;
445e8d8bef9SDimitry Andric 
446*fe6060f1SDimitry Andric     for (auto &KV : NewIndices)
447*fe6060f1SDimitry Andric       Value2Index.insert(KV);
448e8d8bef9SDimitry Andric 
449*fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "Adding " << *CB.Condition << " " << CB.Not << "\n");
450*fe6060f1SDimitry Andric     bool Added = false;
451*fe6060f1SDimitry Andric     for (auto &C : R) {
452*fe6060f1SDimitry Andric       auto Coeffs = C.Coefficients;
453*fe6060f1SDimitry Andric       LLVM_DEBUG({
454*fe6060f1SDimitry Andric         dbgs() << "  constraint: ";
455*fe6060f1SDimitry Andric         dumpWithNames(C, Value2Index);
456*fe6060f1SDimitry Andric       });
457*fe6060f1SDimitry Andric       Added |= CS.addVariableRowFill(Coeffs);
458e8d8bef9SDimitry Andric       // If R has been added to the system, queue it for removal once it goes
459e8d8bef9SDimitry Andric       // out-of-scope.
460*fe6060f1SDimitry Andric       if (Added)
461e8d8bef9SDimitry Andric         DFSInStack.emplace_back(CB.NumIn, CB.NumOut, CB.Condition, CB.Not);
462e8d8bef9SDimitry Andric     }
463*fe6060f1SDimitry Andric   }
464e8d8bef9SDimitry Andric 
465*fe6060f1SDimitry Andric   assert(CS.size() == DFSInStack.size() &&
466*fe6060f1SDimitry Andric          "updates to CS and DFSInStack are out of sync");
467e8d8bef9SDimitry Andric   return Changed;
468e8d8bef9SDimitry Andric }
469e8d8bef9SDimitry Andric 
470e8d8bef9SDimitry Andric PreservedAnalyses ConstraintEliminationPass::run(Function &F,
471e8d8bef9SDimitry Andric                                                  FunctionAnalysisManager &AM) {
472e8d8bef9SDimitry Andric   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
473e8d8bef9SDimitry Andric   if (!eliminateConstraints(F, DT))
474e8d8bef9SDimitry Andric     return PreservedAnalyses::all();
475e8d8bef9SDimitry Andric 
476e8d8bef9SDimitry Andric   PreservedAnalyses PA;
477e8d8bef9SDimitry Andric   PA.preserve<DominatorTreeAnalysis>();
478e8d8bef9SDimitry Andric   PA.preserveSet<CFGAnalyses>();
479e8d8bef9SDimitry Andric   return PA;
480e8d8bef9SDimitry Andric }
481e8d8bef9SDimitry Andric 
482e8d8bef9SDimitry Andric namespace {
483e8d8bef9SDimitry Andric 
484e8d8bef9SDimitry Andric class ConstraintElimination : public FunctionPass {
485e8d8bef9SDimitry Andric public:
486e8d8bef9SDimitry Andric   static char ID;
487e8d8bef9SDimitry Andric 
488e8d8bef9SDimitry Andric   ConstraintElimination() : FunctionPass(ID) {
489e8d8bef9SDimitry Andric     initializeConstraintEliminationPass(*PassRegistry::getPassRegistry());
490e8d8bef9SDimitry Andric   }
491e8d8bef9SDimitry Andric 
492e8d8bef9SDimitry Andric   bool runOnFunction(Function &F) override {
493e8d8bef9SDimitry Andric     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
494e8d8bef9SDimitry Andric     return eliminateConstraints(F, DT);
495e8d8bef9SDimitry Andric   }
496e8d8bef9SDimitry Andric 
497e8d8bef9SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
498e8d8bef9SDimitry Andric     AU.setPreservesCFG();
499e8d8bef9SDimitry Andric     AU.addRequired<DominatorTreeWrapperPass>();
500e8d8bef9SDimitry Andric     AU.addPreserved<GlobalsAAWrapperPass>();
501e8d8bef9SDimitry Andric     AU.addPreserved<DominatorTreeWrapperPass>();
502e8d8bef9SDimitry Andric   }
503e8d8bef9SDimitry Andric };
504e8d8bef9SDimitry Andric 
505e8d8bef9SDimitry Andric } // end anonymous namespace
506e8d8bef9SDimitry Andric 
507e8d8bef9SDimitry Andric char ConstraintElimination::ID = 0;
508e8d8bef9SDimitry Andric 
509e8d8bef9SDimitry Andric INITIALIZE_PASS_BEGIN(ConstraintElimination, "constraint-elimination",
510e8d8bef9SDimitry Andric                       "Constraint Elimination", false, false)
511e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
512e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
513e8d8bef9SDimitry Andric INITIALIZE_PASS_END(ConstraintElimination, "constraint-elimination",
514e8d8bef9SDimitry Andric                     "Constraint Elimination", false, false)
515e8d8bef9SDimitry Andric 
516e8d8bef9SDimitry Andric FunctionPass *llvm::createConstraintEliminationPass() {
517e8d8bef9SDimitry Andric   return new ConstraintElimination();
518e8d8bef9SDimitry Andric }
519