xref: /aosp_15_r20/external/llvm/lib/Analysis/InstructionSimplify.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker //                     The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This file implements routines for folding instructions into simpler forms
11*9880d681SAndroid Build Coastguard Worker // that do not require creating new instructions.  This does constant folding
12*9880d681SAndroid Build Coastguard Worker // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
13*9880d681SAndroid Build Coastguard Worker // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
14*9880d681SAndroid Build Coastguard Worker // ("and i32 %x, %x" -> "%x").  All operands are assumed to have already been
15*9880d681SAndroid Build Coastguard Worker // simplified: This is usually true and assuming it simplifies the logic (if
16*9880d681SAndroid Build Coastguard Worker // they have not been simplified then results are correct but maybe suboptimal).
17*9880d681SAndroid Build Coastguard Worker //
18*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
19*9880d681SAndroid Build Coastguard Worker 
20*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/InstructionSimplify.h"
21*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SetVector.h"
22*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
23*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/AliasAnalysis.h"
24*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/CaptureTracking.h"
25*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ConstantFolding.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/MemoryBuiltins.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ValueTracking.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/VectorUtils.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/ConstantRange.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DataLayout.h"
31*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Dominators.h"
32*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/GetElementPtrTypeIterator.h"
33*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/GlobalAlias.h"
34*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Operator.h"
35*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/PatternMatch.h"
36*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/ValueHandle.h"
37*9880d681SAndroid Build Coastguard Worker #include <algorithm>
38*9880d681SAndroid Build Coastguard Worker using namespace llvm;
39*9880d681SAndroid Build Coastguard Worker using namespace llvm::PatternMatch;
40*9880d681SAndroid Build Coastguard Worker 
41*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "instsimplify"
42*9880d681SAndroid Build Coastguard Worker 
43*9880d681SAndroid Build Coastguard Worker enum { RecursionLimit = 3 };
44*9880d681SAndroid Build Coastguard Worker 
45*9880d681SAndroid Build Coastguard Worker STATISTIC(NumExpand,  "Number of expansions");
46*9880d681SAndroid Build Coastguard Worker STATISTIC(NumReassoc, "Number of reassociations");
47*9880d681SAndroid Build Coastguard Worker 
48*9880d681SAndroid Build Coastguard Worker namespace {
49*9880d681SAndroid Build Coastguard Worker struct Query {
50*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL;
51*9880d681SAndroid Build Coastguard Worker   const TargetLibraryInfo *TLI;
52*9880d681SAndroid Build Coastguard Worker   const DominatorTree *DT;
53*9880d681SAndroid Build Coastguard Worker   AssumptionCache *AC;
54*9880d681SAndroid Build Coastguard Worker   const Instruction *CxtI;
55*9880d681SAndroid Build Coastguard Worker 
Query__anonb03c1e8a0211::Query56*9880d681SAndroid Build Coastguard Worker   Query(const DataLayout &DL, const TargetLibraryInfo *tli,
57*9880d681SAndroid Build Coastguard Worker         const DominatorTree *dt, AssumptionCache *ac = nullptr,
58*9880d681SAndroid Build Coastguard Worker         const Instruction *cxti = nullptr)
59*9880d681SAndroid Build Coastguard Worker       : DL(DL), TLI(tli), DT(dt), AC(ac), CxtI(cxti) {}
60*9880d681SAndroid Build Coastguard Worker };
61*9880d681SAndroid Build Coastguard Worker } // end anonymous namespace
62*9880d681SAndroid Build Coastguard Worker 
63*9880d681SAndroid Build Coastguard Worker static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
64*9880d681SAndroid Build Coastguard Worker static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
65*9880d681SAndroid Build Coastguard Worker                             unsigned);
66*9880d681SAndroid Build Coastguard Worker static Value *SimplifyFPBinOp(unsigned, Value *, Value *, const FastMathFlags &,
67*9880d681SAndroid Build Coastguard Worker                               const Query &, unsigned);
68*9880d681SAndroid Build Coastguard Worker static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
69*9880d681SAndroid Build Coastguard Worker                               unsigned);
70*9880d681SAndroid Build Coastguard Worker static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
71*9880d681SAndroid Build Coastguard Worker static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
72*9880d681SAndroid Build Coastguard Worker static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
73*9880d681SAndroid Build Coastguard Worker 
74*9880d681SAndroid Build Coastguard Worker /// For a boolean type, or a vector of boolean type, return false, or
75*9880d681SAndroid Build Coastguard Worker /// a vector with every element false, as appropriate for the type.
getFalse(Type * Ty)76*9880d681SAndroid Build Coastguard Worker static Constant *getFalse(Type *Ty) {
77*9880d681SAndroid Build Coastguard Worker   assert(Ty->getScalarType()->isIntegerTy(1) &&
78*9880d681SAndroid Build Coastguard Worker          "Expected i1 type or a vector of i1!");
79*9880d681SAndroid Build Coastguard Worker   return Constant::getNullValue(Ty);
80*9880d681SAndroid Build Coastguard Worker }
81*9880d681SAndroid Build Coastguard Worker 
82*9880d681SAndroid Build Coastguard Worker /// For a boolean type, or a vector of boolean type, return true, or
83*9880d681SAndroid Build Coastguard Worker /// a vector with every element true, as appropriate for the type.
getTrue(Type * Ty)84*9880d681SAndroid Build Coastguard Worker static Constant *getTrue(Type *Ty) {
85*9880d681SAndroid Build Coastguard Worker   assert(Ty->getScalarType()->isIntegerTy(1) &&
86*9880d681SAndroid Build Coastguard Worker          "Expected i1 type or a vector of i1!");
87*9880d681SAndroid Build Coastguard Worker   return Constant::getAllOnesValue(Ty);
88*9880d681SAndroid Build Coastguard Worker }
89*9880d681SAndroid Build Coastguard Worker 
90*9880d681SAndroid Build Coastguard Worker /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
isSameCompare(Value * V,CmpInst::Predicate Pred,Value * LHS,Value * RHS)91*9880d681SAndroid Build Coastguard Worker static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
92*9880d681SAndroid Build Coastguard Worker                           Value *RHS) {
93*9880d681SAndroid Build Coastguard Worker   CmpInst *Cmp = dyn_cast<CmpInst>(V);
94*9880d681SAndroid Build Coastguard Worker   if (!Cmp)
95*9880d681SAndroid Build Coastguard Worker     return false;
96*9880d681SAndroid Build Coastguard Worker   CmpInst::Predicate CPred = Cmp->getPredicate();
97*9880d681SAndroid Build Coastguard Worker   Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
98*9880d681SAndroid Build Coastguard Worker   if (CPred == Pred && CLHS == LHS && CRHS == RHS)
99*9880d681SAndroid Build Coastguard Worker     return true;
100*9880d681SAndroid Build Coastguard Worker   return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
101*9880d681SAndroid Build Coastguard Worker     CRHS == LHS;
102*9880d681SAndroid Build Coastguard Worker }
103*9880d681SAndroid Build Coastguard Worker 
104*9880d681SAndroid Build Coastguard Worker /// Does the given value dominate the specified phi node?
ValueDominatesPHI(Value * V,PHINode * P,const DominatorTree * DT)105*9880d681SAndroid Build Coastguard Worker static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
106*9880d681SAndroid Build Coastguard Worker   Instruction *I = dyn_cast<Instruction>(V);
107*9880d681SAndroid Build Coastguard Worker   if (!I)
108*9880d681SAndroid Build Coastguard Worker     // Arguments and constants dominate all instructions.
109*9880d681SAndroid Build Coastguard Worker     return true;
110*9880d681SAndroid Build Coastguard Worker 
111*9880d681SAndroid Build Coastguard Worker   // If we are processing instructions (and/or basic blocks) that have not been
112*9880d681SAndroid Build Coastguard Worker   // fully added to a function, the parent nodes may still be null. Simply
113*9880d681SAndroid Build Coastguard Worker   // return the conservative answer in these cases.
114*9880d681SAndroid Build Coastguard Worker   if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
115*9880d681SAndroid Build Coastguard Worker     return false;
116*9880d681SAndroid Build Coastguard Worker 
117*9880d681SAndroid Build Coastguard Worker   // If we have a DominatorTree then do a precise test.
118*9880d681SAndroid Build Coastguard Worker   if (DT) {
119*9880d681SAndroid Build Coastguard Worker     if (!DT->isReachableFromEntry(P->getParent()))
120*9880d681SAndroid Build Coastguard Worker       return true;
121*9880d681SAndroid Build Coastguard Worker     if (!DT->isReachableFromEntry(I->getParent()))
122*9880d681SAndroid Build Coastguard Worker       return false;
123*9880d681SAndroid Build Coastguard Worker     return DT->dominates(I, P);
124*9880d681SAndroid Build Coastguard Worker   }
125*9880d681SAndroid Build Coastguard Worker 
126*9880d681SAndroid Build Coastguard Worker   // Otherwise, if the instruction is in the entry block and is not an invoke,
127*9880d681SAndroid Build Coastguard Worker   // then it obviously dominates all phi nodes.
128*9880d681SAndroid Build Coastguard Worker   if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
129*9880d681SAndroid Build Coastguard Worker       !isa<InvokeInst>(I))
130*9880d681SAndroid Build Coastguard Worker     return true;
131*9880d681SAndroid Build Coastguard Worker 
132*9880d681SAndroid Build Coastguard Worker   return false;
133*9880d681SAndroid Build Coastguard Worker }
134*9880d681SAndroid Build Coastguard Worker 
135*9880d681SAndroid Build Coastguard Worker /// Simplify "A op (B op' C)" by distributing op over op', turning it into
136*9880d681SAndroid Build Coastguard Worker /// "(A op B) op' (A op C)".  Here "op" is given by Opcode and "op'" is
137*9880d681SAndroid Build Coastguard Worker /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
138*9880d681SAndroid Build Coastguard Worker /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
139*9880d681SAndroid Build Coastguard Worker /// Returns the simplified value, or null if no simplification was performed.
ExpandBinOp(unsigned Opcode,Value * LHS,Value * RHS,unsigned OpcToExpand,const Query & Q,unsigned MaxRecurse)140*9880d681SAndroid Build Coastguard Worker static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
141*9880d681SAndroid Build Coastguard Worker                           unsigned OpcToExpand, const Query &Q,
142*9880d681SAndroid Build Coastguard Worker                           unsigned MaxRecurse) {
143*9880d681SAndroid Build Coastguard Worker   Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
144*9880d681SAndroid Build Coastguard Worker   // Recursion is always used, so bail out at once if we already hit the limit.
145*9880d681SAndroid Build Coastguard Worker   if (!MaxRecurse--)
146*9880d681SAndroid Build Coastguard Worker     return nullptr;
147*9880d681SAndroid Build Coastguard Worker 
148*9880d681SAndroid Build Coastguard Worker   // Check whether the expression has the form "(A op' B) op C".
149*9880d681SAndroid Build Coastguard Worker   if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
150*9880d681SAndroid Build Coastguard Worker     if (Op0->getOpcode() == OpcodeToExpand) {
151*9880d681SAndroid Build Coastguard Worker       // It does!  Try turning it into "(A op C) op' (B op C)".
152*9880d681SAndroid Build Coastguard Worker       Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
153*9880d681SAndroid Build Coastguard Worker       // Do "A op C" and "B op C" both simplify?
154*9880d681SAndroid Build Coastguard Worker       if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
155*9880d681SAndroid Build Coastguard Worker         if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
156*9880d681SAndroid Build Coastguard Worker           // They do! Return "L op' R" if it simplifies or is already available.
157*9880d681SAndroid Build Coastguard Worker           // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
158*9880d681SAndroid Build Coastguard Worker           if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
159*9880d681SAndroid Build Coastguard Worker                                      && L == B && R == A)) {
160*9880d681SAndroid Build Coastguard Worker             ++NumExpand;
161*9880d681SAndroid Build Coastguard Worker             return LHS;
162*9880d681SAndroid Build Coastguard Worker           }
163*9880d681SAndroid Build Coastguard Worker           // Otherwise return "L op' R" if it simplifies.
164*9880d681SAndroid Build Coastguard Worker           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
165*9880d681SAndroid Build Coastguard Worker             ++NumExpand;
166*9880d681SAndroid Build Coastguard Worker             return V;
167*9880d681SAndroid Build Coastguard Worker           }
168*9880d681SAndroid Build Coastguard Worker         }
169*9880d681SAndroid Build Coastguard Worker     }
170*9880d681SAndroid Build Coastguard Worker 
171*9880d681SAndroid Build Coastguard Worker   // Check whether the expression has the form "A op (B op' C)".
172*9880d681SAndroid Build Coastguard Worker   if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
173*9880d681SAndroid Build Coastguard Worker     if (Op1->getOpcode() == OpcodeToExpand) {
174*9880d681SAndroid Build Coastguard Worker       // It does!  Try turning it into "(A op B) op' (A op C)".
175*9880d681SAndroid Build Coastguard Worker       Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
176*9880d681SAndroid Build Coastguard Worker       // Do "A op B" and "A op C" both simplify?
177*9880d681SAndroid Build Coastguard Worker       if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
178*9880d681SAndroid Build Coastguard Worker         if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
179*9880d681SAndroid Build Coastguard Worker           // They do! Return "L op' R" if it simplifies or is already available.
180*9880d681SAndroid Build Coastguard Worker           // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
181*9880d681SAndroid Build Coastguard Worker           if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
182*9880d681SAndroid Build Coastguard Worker                                      && L == C && R == B)) {
183*9880d681SAndroid Build Coastguard Worker             ++NumExpand;
184*9880d681SAndroid Build Coastguard Worker             return RHS;
185*9880d681SAndroid Build Coastguard Worker           }
186*9880d681SAndroid Build Coastguard Worker           // Otherwise return "L op' R" if it simplifies.
187*9880d681SAndroid Build Coastguard Worker           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
188*9880d681SAndroid Build Coastguard Worker             ++NumExpand;
189*9880d681SAndroid Build Coastguard Worker             return V;
190*9880d681SAndroid Build Coastguard Worker           }
191*9880d681SAndroid Build Coastguard Worker         }
192*9880d681SAndroid Build Coastguard Worker     }
193*9880d681SAndroid Build Coastguard Worker 
194*9880d681SAndroid Build Coastguard Worker   return nullptr;
195*9880d681SAndroid Build Coastguard Worker }
196*9880d681SAndroid Build Coastguard Worker 
197*9880d681SAndroid Build Coastguard Worker /// Generic simplifications for associative binary operations.
198*9880d681SAndroid Build Coastguard Worker /// Returns the simpler value, or null if none was found.
SimplifyAssociativeBinOp(unsigned Opc,Value * LHS,Value * RHS,const Query & Q,unsigned MaxRecurse)199*9880d681SAndroid Build Coastguard Worker static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
200*9880d681SAndroid Build Coastguard Worker                                        const Query &Q, unsigned MaxRecurse) {
201*9880d681SAndroid Build Coastguard Worker   Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
202*9880d681SAndroid Build Coastguard Worker   assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
203*9880d681SAndroid Build Coastguard Worker 
204*9880d681SAndroid Build Coastguard Worker   // Recursion is always used, so bail out at once if we already hit the limit.
205*9880d681SAndroid Build Coastguard Worker   if (!MaxRecurse--)
206*9880d681SAndroid Build Coastguard Worker     return nullptr;
207*9880d681SAndroid Build Coastguard Worker 
208*9880d681SAndroid Build Coastguard Worker   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
209*9880d681SAndroid Build Coastguard Worker   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
210*9880d681SAndroid Build Coastguard Worker 
211*9880d681SAndroid Build Coastguard Worker   // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
212*9880d681SAndroid Build Coastguard Worker   if (Op0 && Op0->getOpcode() == Opcode) {
213*9880d681SAndroid Build Coastguard Worker     Value *A = Op0->getOperand(0);
214*9880d681SAndroid Build Coastguard Worker     Value *B = Op0->getOperand(1);
215*9880d681SAndroid Build Coastguard Worker     Value *C = RHS;
216*9880d681SAndroid Build Coastguard Worker 
217*9880d681SAndroid Build Coastguard Worker     // Does "B op C" simplify?
218*9880d681SAndroid Build Coastguard Worker     if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
219*9880d681SAndroid Build Coastguard Worker       // It does!  Return "A op V" if it simplifies or is already available.
220*9880d681SAndroid Build Coastguard Worker       // If V equals B then "A op V" is just the LHS.
221*9880d681SAndroid Build Coastguard Worker       if (V == B) return LHS;
222*9880d681SAndroid Build Coastguard Worker       // Otherwise return "A op V" if it simplifies.
223*9880d681SAndroid Build Coastguard Worker       if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
224*9880d681SAndroid Build Coastguard Worker         ++NumReassoc;
225*9880d681SAndroid Build Coastguard Worker         return W;
226*9880d681SAndroid Build Coastguard Worker       }
227*9880d681SAndroid Build Coastguard Worker     }
228*9880d681SAndroid Build Coastguard Worker   }
229*9880d681SAndroid Build Coastguard Worker 
230*9880d681SAndroid Build Coastguard Worker   // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
231*9880d681SAndroid Build Coastguard Worker   if (Op1 && Op1->getOpcode() == Opcode) {
232*9880d681SAndroid Build Coastguard Worker     Value *A = LHS;
233*9880d681SAndroid Build Coastguard Worker     Value *B = Op1->getOperand(0);
234*9880d681SAndroid Build Coastguard Worker     Value *C = Op1->getOperand(1);
235*9880d681SAndroid Build Coastguard Worker 
236*9880d681SAndroid Build Coastguard Worker     // Does "A op B" simplify?
237*9880d681SAndroid Build Coastguard Worker     if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
238*9880d681SAndroid Build Coastguard Worker       // It does!  Return "V op C" if it simplifies or is already available.
239*9880d681SAndroid Build Coastguard Worker       // If V equals B then "V op C" is just the RHS.
240*9880d681SAndroid Build Coastguard Worker       if (V == B) return RHS;
241*9880d681SAndroid Build Coastguard Worker       // Otherwise return "V op C" if it simplifies.
242*9880d681SAndroid Build Coastguard Worker       if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
243*9880d681SAndroid Build Coastguard Worker         ++NumReassoc;
244*9880d681SAndroid Build Coastguard Worker         return W;
245*9880d681SAndroid Build Coastguard Worker       }
246*9880d681SAndroid Build Coastguard Worker     }
247*9880d681SAndroid Build Coastguard Worker   }
248*9880d681SAndroid Build Coastguard Worker 
249*9880d681SAndroid Build Coastguard Worker   // The remaining transforms require commutativity as well as associativity.
250*9880d681SAndroid Build Coastguard Worker   if (!Instruction::isCommutative(Opcode))
251*9880d681SAndroid Build Coastguard Worker     return nullptr;
252*9880d681SAndroid Build Coastguard Worker 
253*9880d681SAndroid Build Coastguard Worker   // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
254*9880d681SAndroid Build Coastguard Worker   if (Op0 && Op0->getOpcode() == Opcode) {
255*9880d681SAndroid Build Coastguard Worker     Value *A = Op0->getOperand(0);
256*9880d681SAndroid Build Coastguard Worker     Value *B = Op0->getOperand(1);
257*9880d681SAndroid Build Coastguard Worker     Value *C = RHS;
258*9880d681SAndroid Build Coastguard Worker 
259*9880d681SAndroid Build Coastguard Worker     // Does "C op A" simplify?
260*9880d681SAndroid Build Coastguard Worker     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
261*9880d681SAndroid Build Coastguard Worker       // It does!  Return "V op B" if it simplifies or is already available.
262*9880d681SAndroid Build Coastguard Worker       // If V equals A then "V op B" is just the LHS.
263*9880d681SAndroid Build Coastguard Worker       if (V == A) return LHS;
264*9880d681SAndroid Build Coastguard Worker       // Otherwise return "V op B" if it simplifies.
265*9880d681SAndroid Build Coastguard Worker       if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
266*9880d681SAndroid Build Coastguard Worker         ++NumReassoc;
267*9880d681SAndroid Build Coastguard Worker         return W;
268*9880d681SAndroid Build Coastguard Worker       }
269*9880d681SAndroid Build Coastguard Worker     }
270*9880d681SAndroid Build Coastguard Worker   }
271*9880d681SAndroid Build Coastguard Worker 
272*9880d681SAndroid Build Coastguard Worker   // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
273*9880d681SAndroid Build Coastguard Worker   if (Op1 && Op1->getOpcode() == Opcode) {
274*9880d681SAndroid Build Coastguard Worker     Value *A = LHS;
275*9880d681SAndroid Build Coastguard Worker     Value *B = Op1->getOperand(0);
276*9880d681SAndroid Build Coastguard Worker     Value *C = Op1->getOperand(1);
277*9880d681SAndroid Build Coastguard Worker 
278*9880d681SAndroid Build Coastguard Worker     // Does "C op A" simplify?
279*9880d681SAndroid Build Coastguard Worker     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
280*9880d681SAndroid Build Coastguard Worker       // It does!  Return "B op V" if it simplifies or is already available.
281*9880d681SAndroid Build Coastguard Worker       // If V equals C then "B op V" is just the RHS.
282*9880d681SAndroid Build Coastguard Worker       if (V == C) return RHS;
283*9880d681SAndroid Build Coastguard Worker       // Otherwise return "B op V" if it simplifies.
284*9880d681SAndroid Build Coastguard Worker       if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
285*9880d681SAndroid Build Coastguard Worker         ++NumReassoc;
286*9880d681SAndroid Build Coastguard Worker         return W;
287*9880d681SAndroid Build Coastguard Worker       }
288*9880d681SAndroid Build Coastguard Worker     }
289*9880d681SAndroid Build Coastguard Worker   }
290*9880d681SAndroid Build Coastguard Worker 
291*9880d681SAndroid Build Coastguard Worker   return nullptr;
292*9880d681SAndroid Build Coastguard Worker }
293*9880d681SAndroid Build Coastguard Worker 
294*9880d681SAndroid Build Coastguard Worker /// In the case of a binary operation with a select instruction as an operand,
295*9880d681SAndroid Build Coastguard Worker /// try to simplify the binop by seeing whether evaluating it on both branches
296*9880d681SAndroid Build Coastguard Worker /// of the select results in the same value. Returns the common value if so,
297*9880d681SAndroid Build Coastguard Worker /// otherwise returns null.
ThreadBinOpOverSelect(unsigned Opcode,Value * LHS,Value * RHS,const Query & Q,unsigned MaxRecurse)298*9880d681SAndroid Build Coastguard Worker static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
299*9880d681SAndroid Build Coastguard Worker                                     const Query &Q, unsigned MaxRecurse) {
300*9880d681SAndroid Build Coastguard Worker   // Recursion is always used, so bail out at once if we already hit the limit.
301*9880d681SAndroid Build Coastguard Worker   if (!MaxRecurse--)
302*9880d681SAndroid Build Coastguard Worker     return nullptr;
303*9880d681SAndroid Build Coastguard Worker 
304*9880d681SAndroid Build Coastguard Worker   SelectInst *SI;
305*9880d681SAndroid Build Coastguard Worker   if (isa<SelectInst>(LHS)) {
306*9880d681SAndroid Build Coastguard Worker     SI = cast<SelectInst>(LHS);
307*9880d681SAndroid Build Coastguard Worker   } else {
308*9880d681SAndroid Build Coastguard Worker     assert(isa<SelectInst>(RHS) && "No select instruction operand!");
309*9880d681SAndroid Build Coastguard Worker     SI = cast<SelectInst>(RHS);
310*9880d681SAndroid Build Coastguard Worker   }
311*9880d681SAndroid Build Coastguard Worker 
312*9880d681SAndroid Build Coastguard Worker   // Evaluate the BinOp on the true and false branches of the select.
313*9880d681SAndroid Build Coastguard Worker   Value *TV;
314*9880d681SAndroid Build Coastguard Worker   Value *FV;
315*9880d681SAndroid Build Coastguard Worker   if (SI == LHS) {
316*9880d681SAndroid Build Coastguard Worker     TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
317*9880d681SAndroid Build Coastguard Worker     FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
318*9880d681SAndroid Build Coastguard Worker   } else {
319*9880d681SAndroid Build Coastguard Worker     TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
320*9880d681SAndroid Build Coastguard Worker     FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
321*9880d681SAndroid Build Coastguard Worker   }
322*9880d681SAndroid Build Coastguard Worker 
323*9880d681SAndroid Build Coastguard Worker   // If they simplified to the same value, then return the common value.
324*9880d681SAndroid Build Coastguard Worker   // If they both failed to simplify then return null.
325*9880d681SAndroid Build Coastguard Worker   if (TV == FV)
326*9880d681SAndroid Build Coastguard Worker     return TV;
327*9880d681SAndroid Build Coastguard Worker 
328*9880d681SAndroid Build Coastguard Worker   // If one branch simplified to undef, return the other one.
329*9880d681SAndroid Build Coastguard Worker   if (TV && isa<UndefValue>(TV))
330*9880d681SAndroid Build Coastguard Worker     return FV;
331*9880d681SAndroid Build Coastguard Worker   if (FV && isa<UndefValue>(FV))
332*9880d681SAndroid Build Coastguard Worker     return TV;
333*9880d681SAndroid Build Coastguard Worker 
334*9880d681SAndroid Build Coastguard Worker   // If applying the operation did not change the true and false select values,
335*9880d681SAndroid Build Coastguard Worker   // then the result of the binop is the select itself.
336*9880d681SAndroid Build Coastguard Worker   if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
337*9880d681SAndroid Build Coastguard Worker     return SI;
338*9880d681SAndroid Build Coastguard Worker 
339*9880d681SAndroid Build Coastguard Worker   // If one branch simplified and the other did not, and the simplified
340*9880d681SAndroid Build Coastguard Worker   // value is equal to the unsimplified one, return the simplified value.
341*9880d681SAndroid Build Coastguard Worker   // For example, select (cond, X, X & Z) & Z -> X & Z.
342*9880d681SAndroid Build Coastguard Worker   if ((FV && !TV) || (TV && !FV)) {
343*9880d681SAndroid Build Coastguard Worker     // Check that the simplified value has the form "X op Y" where "op" is the
344*9880d681SAndroid Build Coastguard Worker     // same as the original operation.
345*9880d681SAndroid Build Coastguard Worker     Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
346*9880d681SAndroid Build Coastguard Worker     if (Simplified && Simplified->getOpcode() == Opcode) {
347*9880d681SAndroid Build Coastguard Worker       // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
348*9880d681SAndroid Build Coastguard Worker       // We already know that "op" is the same as for the simplified value.  See
349*9880d681SAndroid Build Coastguard Worker       // if the operands match too.  If so, return the simplified value.
350*9880d681SAndroid Build Coastguard Worker       Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
351*9880d681SAndroid Build Coastguard Worker       Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
352*9880d681SAndroid Build Coastguard Worker       Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
353*9880d681SAndroid Build Coastguard Worker       if (Simplified->getOperand(0) == UnsimplifiedLHS &&
354*9880d681SAndroid Build Coastguard Worker           Simplified->getOperand(1) == UnsimplifiedRHS)
355*9880d681SAndroid Build Coastguard Worker         return Simplified;
356*9880d681SAndroid Build Coastguard Worker       if (Simplified->isCommutative() &&
357*9880d681SAndroid Build Coastguard Worker           Simplified->getOperand(1) == UnsimplifiedLHS &&
358*9880d681SAndroid Build Coastguard Worker           Simplified->getOperand(0) == UnsimplifiedRHS)
359*9880d681SAndroid Build Coastguard Worker         return Simplified;
360*9880d681SAndroid Build Coastguard Worker     }
361*9880d681SAndroid Build Coastguard Worker   }
362*9880d681SAndroid Build Coastguard Worker 
363*9880d681SAndroid Build Coastguard Worker   return nullptr;
364*9880d681SAndroid Build Coastguard Worker }
365*9880d681SAndroid Build Coastguard Worker 
366*9880d681SAndroid Build Coastguard Worker /// In the case of a comparison with a select instruction, try to simplify the
367*9880d681SAndroid Build Coastguard Worker /// comparison by seeing whether both branches of the select result in the same
368*9880d681SAndroid Build Coastguard Worker /// value. Returns the common value if so, otherwise returns null.
ThreadCmpOverSelect(CmpInst::Predicate Pred,Value * LHS,Value * RHS,const Query & Q,unsigned MaxRecurse)369*9880d681SAndroid Build Coastguard Worker static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
370*9880d681SAndroid Build Coastguard Worker                                   Value *RHS, const Query &Q,
371*9880d681SAndroid Build Coastguard Worker                                   unsigned MaxRecurse) {
372*9880d681SAndroid Build Coastguard Worker   // Recursion is always used, so bail out at once if we already hit the limit.
373*9880d681SAndroid Build Coastguard Worker   if (!MaxRecurse--)
374*9880d681SAndroid Build Coastguard Worker     return nullptr;
375*9880d681SAndroid Build Coastguard Worker 
376*9880d681SAndroid Build Coastguard Worker   // Make sure the select is on the LHS.
377*9880d681SAndroid Build Coastguard Worker   if (!isa<SelectInst>(LHS)) {
378*9880d681SAndroid Build Coastguard Worker     std::swap(LHS, RHS);
379*9880d681SAndroid Build Coastguard Worker     Pred = CmpInst::getSwappedPredicate(Pred);
380*9880d681SAndroid Build Coastguard Worker   }
381*9880d681SAndroid Build Coastguard Worker   assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
382*9880d681SAndroid Build Coastguard Worker   SelectInst *SI = cast<SelectInst>(LHS);
383*9880d681SAndroid Build Coastguard Worker   Value *Cond = SI->getCondition();
384*9880d681SAndroid Build Coastguard Worker   Value *TV = SI->getTrueValue();
385*9880d681SAndroid Build Coastguard Worker   Value *FV = SI->getFalseValue();
386*9880d681SAndroid Build Coastguard Worker 
387*9880d681SAndroid Build Coastguard Worker   // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
388*9880d681SAndroid Build Coastguard Worker   // Does "cmp TV, RHS" simplify?
389*9880d681SAndroid Build Coastguard Worker   Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
390*9880d681SAndroid Build Coastguard Worker   if (TCmp == Cond) {
391*9880d681SAndroid Build Coastguard Worker     // It not only simplified, it simplified to the select condition.  Replace
392*9880d681SAndroid Build Coastguard Worker     // it with 'true'.
393*9880d681SAndroid Build Coastguard Worker     TCmp = getTrue(Cond->getType());
394*9880d681SAndroid Build Coastguard Worker   } else if (!TCmp) {
395*9880d681SAndroid Build Coastguard Worker     // It didn't simplify.  However if "cmp TV, RHS" is equal to the select
396*9880d681SAndroid Build Coastguard Worker     // condition then we can replace it with 'true'.  Otherwise give up.
397*9880d681SAndroid Build Coastguard Worker     if (!isSameCompare(Cond, Pred, TV, RHS))
398*9880d681SAndroid Build Coastguard Worker       return nullptr;
399*9880d681SAndroid Build Coastguard Worker     TCmp = getTrue(Cond->getType());
400*9880d681SAndroid Build Coastguard Worker   }
401*9880d681SAndroid Build Coastguard Worker 
402*9880d681SAndroid Build Coastguard Worker   // Does "cmp FV, RHS" simplify?
403*9880d681SAndroid Build Coastguard Worker   Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
404*9880d681SAndroid Build Coastguard Worker   if (FCmp == Cond) {
405*9880d681SAndroid Build Coastguard Worker     // It not only simplified, it simplified to the select condition.  Replace
406*9880d681SAndroid Build Coastguard Worker     // it with 'false'.
407*9880d681SAndroid Build Coastguard Worker     FCmp = getFalse(Cond->getType());
408*9880d681SAndroid Build Coastguard Worker   } else if (!FCmp) {
409*9880d681SAndroid Build Coastguard Worker     // It didn't simplify.  However if "cmp FV, RHS" is equal to the select
410*9880d681SAndroid Build Coastguard Worker     // condition then we can replace it with 'false'.  Otherwise give up.
411*9880d681SAndroid Build Coastguard Worker     if (!isSameCompare(Cond, Pred, FV, RHS))
412*9880d681SAndroid Build Coastguard Worker       return nullptr;
413*9880d681SAndroid Build Coastguard Worker     FCmp = getFalse(Cond->getType());
414*9880d681SAndroid Build Coastguard Worker   }
415*9880d681SAndroid Build Coastguard Worker 
416*9880d681SAndroid Build Coastguard Worker   // If both sides simplified to the same value, then use it as the result of
417*9880d681SAndroid Build Coastguard Worker   // the original comparison.
418*9880d681SAndroid Build Coastguard Worker   if (TCmp == FCmp)
419*9880d681SAndroid Build Coastguard Worker     return TCmp;
420*9880d681SAndroid Build Coastguard Worker 
421*9880d681SAndroid Build Coastguard Worker   // The remaining cases only make sense if the select condition has the same
422*9880d681SAndroid Build Coastguard Worker   // type as the result of the comparison, so bail out if this is not so.
423*9880d681SAndroid Build Coastguard Worker   if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
424*9880d681SAndroid Build Coastguard Worker     return nullptr;
425*9880d681SAndroid Build Coastguard Worker   // If the false value simplified to false, then the result of the compare
426*9880d681SAndroid Build Coastguard Worker   // is equal to "Cond && TCmp".  This also catches the case when the false
427*9880d681SAndroid Build Coastguard Worker   // value simplified to false and the true value to true, returning "Cond".
428*9880d681SAndroid Build Coastguard Worker   if (match(FCmp, m_Zero()))
429*9880d681SAndroid Build Coastguard Worker     if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
430*9880d681SAndroid Build Coastguard Worker       return V;
431*9880d681SAndroid Build Coastguard Worker   // If the true value simplified to true, then the result of the compare
432*9880d681SAndroid Build Coastguard Worker   // is equal to "Cond || FCmp".
433*9880d681SAndroid Build Coastguard Worker   if (match(TCmp, m_One()))
434*9880d681SAndroid Build Coastguard Worker     if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
435*9880d681SAndroid Build Coastguard Worker       return V;
436*9880d681SAndroid Build Coastguard Worker   // Finally, if the false value simplified to true and the true value to
437*9880d681SAndroid Build Coastguard Worker   // false, then the result of the compare is equal to "!Cond".
438*9880d681SAndroid Build Coastguard Worker   if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
439*9880d681SAndroid Build Coastguard Worker     if (Value *V =
440*9880d681SAndroid Build Coastguard Worker         SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
441*9880d681SAndroid Build Coastguard Worker                         Q, MaxRecurse))
442*9880d681SAndroid Build Coastguard Worker       return V;
443*9880d681SAndroid Build Coastguard Worker 
444*9880d681SAndroid Build Coastguard Worker   return nullptr;
445*9880d681SAndroid Build Coastguard Worker }
446*9880d681SAndroid Build Coastguard Worker 
447*9880d681SAndroid Build Coastguard Worker /// In the case of a binary operation with an operand that is a PHI instruction,
448*9880d681SAndroid Build Coastguard Worker /// try to simplify the binop by seeing whether evaluating it on the incoming
449*9880d681SAndroid Build Coastguard Worker /// phi values yields the same result for every value. If so returns the common
450*9880d681SAndroid Build Coastguard Worker /// value, otherwise returns null.
ThreadBinOpOverPHI(unsigned Opcode,Value * LHS,Value * RHS,const Query & Q,unsigned MaxRecurse)451*9880d681SAndroid Build Coastguard Worker static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
452*9880d681SAndroid Build Coastguard Worker                                  const Query &Q, unsigned MaxRecurse) {
453*9880d681SAndroid Build Coastguard Worker   // Recursion is always used, so bail out at once if we already hit the limit.
454*9880d681SAndroid Build Coastguard Worker   if (!MaxRecurse--)
455*9880d681SAndroid Build Coastguard Worker     return nullptr;
456*9880d681SAndroid Build Coastguard Worker 
457*9880d681SAndroid Build Coastguard Worker   PHINode *PI;
458*9880d681SAndroid Build Coastguard Worker   if (isa<PHINode>(LHS)) {
459*9880d681SAndroid Build Coastguard Worker     PI = cast<PHINode>(LHS);
460*9880d681SAndroid Build Coastguard Worker     // Bail out if RHS and the phi may be mutually interdependent due to a loop.
461*9880d681SAndroid Build Coastguard Worker     if (!ValueDominatesPHI(RHS, PI, Q.DT))
462*9880d681SAndroid Build Coastguard Worker       return nullptr;
463*9880d681SAndroid Build Coastguard Worker   } else {
464*9880d681SAndroid Build Coastguard Worker     assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
465*9880d681SAndroid Build Coastguard Worker     PI = cast<PHINode>(RHS);
466*9880d681SAndroid Build Coastguard Worker     // Bail out if LHS and the phi may be mutually interdependent due to a loop.
467*9880d681SAndroid Build Coastguard Worker     if (!ValueDominatesPHI(LHS, PI, Q.DT))
468*9880d681SAndroid Build Coastguard Worker       return nullptr;
469*9880d681SAndroid Build Coastguard Worker   }
470*9880d681SAndroid Build Coastguard Worker 
471*9880d681SAndroid Build Coastguard Worker   // Evaluate the BinOp on the incoming phi values.
472*9880d681SAndroid Build Coastguard Worker   Value *CommonValue = nullptr;
473*9880d681SAndroid Build Coastguard Worker   for (Value *Incoming : PI->incoming_values()) {
474*9880d681SAndroid Build Coastguard Worker     // If the incoming value is the phi node itself, it can safely be skipped.
475*9880d681SAndroid Build Coastguard Worker     if (Incoming == PI) continue;
476*9880d681SAndroid Build Coastguard Worker     Value *V = PI == LHS ?
477*9880d681SAndroid Build Coastguard Worker       SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
478*9880d681SAndroid Build Coastguard Worker       SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
479*9880d681SAndroid Build Coastguard Worker     // If the operation failed to simplify, or simplified to a different value
480*9880d681SAndroid Build Coastguard Worker     // to previously, then give up.
481*9880d681SAndroid Build Coastguard Worker     if (!V || (CommonValue && V != CommonValue))
482*9880d681SAndroid Build Coastguard Worker       return nullptr;
483*9880d681SAndroid Build Coastguard Worker     CommonValue = V;
484*9880d681SAndroid Build Coastguard Worker   }
485*9880d681SAndroid Build Coastguard Worker 
486*9880d681SAndroid Build Coastguard Worker   return CommonValue;
487*9880d681SAndroid Build Coastguard Worker }
488*9880d681SAndroid Build Coastguard Worker 
489*9880d681SAndroid Build Coastguard Worker /// In the case of a comparison with a PHI instruction, try to simplify the
490*9880d681SAndroid Build Coastguard Worker /// comparison by seeing whether comparing with all of the incoming phi values
491*9880d681SAndroid Build Coastguard Worker /// yields the same result every time. If so returns the common result,
492*9880d681SAndroid Build Coastguard Worker /// otherwise returns null.
ThreadCmpOverPHI(CmpInst::Predicate Pred,Value * LHS,Value * RHS,const Query & Q,unsigned MaxRecurse)493*9880d681SAndroid Build Coastguard Worker static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
494*9880d681SAndroid Build Coastguard Worker                                const Query &Q, unsigned MaxRecurse) {
495*9880d681SAndroid Build Coastguard Worker   // Recursion is always used, so bail out at once if we already hit the limit.
496*9880d681SAndroid Build Coastguard Worker   if (!MaxRecurse--)
497*9880d681SAndroid Build Coastguard Worker     return nullptr;
498*9880d681SAndroid Build Coastguard Worker 
499*9880d681SAndroid Build Coastguard Worker   // Make sure the phi is on the LHS.
500*9880d681SAndroid Build Coastguard Worker   if (!isa<PHINode>(LHS)) {
501*9880d681SAndroid Build Coastguard Worker     std::swap(LHS, RHS);
502*9880d681SAndroid Build Coastguard Worker     Pred = CmpInst::getSwappedPredicate(Pred);
503*9880d681SAndroid Build Coastguard Worker   }
504*9880d681SAndroid Build Coastguard Worker   assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
505*9880d681SAndroid Build Coastguard Worker   PHINode *PI = cast<PHINode>(LHS);
506*9880d681SAndroid Build Coastguard Worker 
507*9880d681SAndroid Build Coastguard Worker   // Bail out if RHS and the phi may be mutually interdependent due to a loop.
508*9880d681SAndroid Build Coastguard Worker   if (!ValueDominatesPHI(RHS, PI, Q.DT))
509*9880d681SAndroid Build Coastguard Worker     return nullptr;
510*9880d681SAndroid Build Coastguard Worker 
511*9880d681SAndroid Build Coastguard Worker   // Evaluate the BinOp on the incoming phi values.
512*9880d681SAndroid Build Coastguard Worker   Value *CommonValue = nullptr;
513*9880d681SAndroid Build Coastguard Worker   for (Value *Incoming : PI->incoming_values()) {
514*9880d681SAndroid Build Coastguard Worker     // If the incoming value is the phi node itself, it can safely be skipped.
515*9880d681SAndroid Build Coastguard Worker     if (Incoming == PI) continue;
516*9880d681SAndroid Build Coastguard Worker     Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
517*9880d681SAndroid Build Coastguard Worker     // If the operation failed to simplify, or simplified to a different value
518*9880d681SAndroid Build Coastguard Worker     // to previously, then give up.
519*9880d681SAndroid Build Coastguard Worker     if (!V || (CommonValue && V != CommonValue))
520*9880d681SAndroid Build Coastguard Worker       return nullptr;
521*9880d681SAndroid Build Coastguard Worker     CommonValue = V;
522*9880d681SAndroid Build Coastguard Worker   }
523*9880d681SAndroid Build Coastguard Worker 
524*9880d681SAndroid Build Coastguard Worker   return CommonValue;
525*9880d681SAndroid Build Coastguard Worker }
526*9880d681SAndroid Build Coastguard Worker 
527*9880d681SAndroid Build Coastguard Worker /// Given operands for an Add, see if we can fold the result.
528*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifyAddInst(Value * Op0,Value * Op1,bool isNSW,bool isNUW,const Query & Q,unsigned MaxRecurse)529*9880d681SAndroid Build Coastguard Worker static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
530*9880d681SAndroid Build Coastguard Worker                               const Query &Q, unsigned MaxRecurse) {
531*9880d681SAndroid Build Coastguard Worker   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
532*9880d681SAndroid Build Coastguard Worker     if (Constant *CRHS = dyn_cast<Constant>(Op1))
533*9880d681SAndroid Build Coastguard Worker       return ConstantFoldBinaryOpOperands(Instruction::Add, CLHS, CRHS, Q.DL);
534*9880d681SAndroid Build Coastguard Worker 
535*9880d681SAndroid Build Coastguard Worker     // Canonicalize the constant to the RHS.
536*9880d681SAndroid Build Coastguard Worker     std::swap(Op0, Op1);
537*9880d681SAndroid Build Coastguard Worker   }
538*9880d681SAndroid Build Coastguard Worker 
539*9880d681SAndroid Build Coastguard Worker   // X + undef -> undef
540*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Undef()))
541*9880d681SAndroid Build Coastguard Worker     return Op1;
542*9880d681SAndroid Build Coastguard Worker 
543*9880d681SAndroid Build Coastguard Worker   // X + 0 -> X
544*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Zero()))
545*9880d681SAndroid Build Coastguard Worker     return Op0;
546*9880d681SAndroid Build Coastguard Worker 
547*9880d681SAndroid Build Coastguard Worker   // X + (Y - X) -> Y
548*9880d681SAndroid Build Coastguard Worker   // (Y - X) + X -> Y
549*9880d681SAndroid Build Coastguard Worker   // Eg: X + -X -> 0
550*9880d681SAndroid Build Coastguard Worker   Value *Y = nullptr;
551*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
552*9880d681SAndroid Build Coastguard Worker       match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
553*9880d681SAndroid Build Coastguard Worker     return Y;
554*9880d681SAndroid Build Coastguard Worker 
555*9880d681SAndroid Build Coastguard Worker   // X + ~X -> -1   since   ~X = -X-1
556*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_Not(m_Specific(Op1))) ||
557*9880d681SAndroid Build Coastguard Worker       match(Op1, m_Not(m_Specific(Op0))))
558*9880d681SAndroid Build Coastguard Worker     return Constant::getAllOnesValue(Op0->getType());
559*9880d681SAndroid Build Coastguard Worker 
560*9880d681SAndroid Build Coastguard Worker   /// i1 add -> xor.
561*9880d681SAndroid Build Coastguard Worker   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
562*9880d681SAndroid Build Coastguard Worker     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
563*9880d681SAndroid Build Coastguard Worker       return V;
564*9880d681SAndroid Build Coastguard Worker 
565*9880d681SAndroid Build Coastguard Worker   // Try some generic simplifications for associative operations.
566*9880d681SAndroid Build Coastguard Worker   if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
567*9880d681SAndroid Build Coastguard Worker                                           MaxRecurse))
568*9880d681SAndroid Build Coastguard Worker     return V;
569*9880d681SAndroid Build Coastguard Worker 
570*9880d681SAndroid Build Coastguard Worker   // Threading Add over selects and phi nodes is pointless, so don't bother.
571*9880d681SAndroid Build Coastguard Worker   // Threading over the select in "A + select(cond, B, C)" means evaluating
572*9880d681SAndroid Build Coastguard Worker   // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
573*9880d681SAndroid Build Coastguard Worker   // only if B and C are equal.  If B and C are equal then (since we assume
574*9880d681SAndroid Build Coastguard Worker   // that operands have already been simplified) "select(cond, B, C)" should
575*9880d681SAndroid Build Coastguard Worker   // have been simplified to the common value of B and C already.  Analysing
576*9880d681SAndroid Build Coastguard Worker   // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
577*9880d681SAndroid Build Coastguard Worker   // for threading over phi nodes.
578*9880d681SAndroid Build Coastguard Worker 
579*9880d681SAndroid Build Coastguard Worker   return nullptr;
580*9880d681SAndroid Build Coastguard Worker }
581*9880d681SAndroid Build Coastguard Worker 
SimplifyAddInst(Value * Op0,Value * Op1,bool isNSW,bool isNUW,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)582*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
583*9880d681SAndroid Build Coastguard Worker                              const DataLayout &DL, const TargetLibraryInfo *TLI,
584*9880d681SAndroid Build Coastguard Worker                              const DominatorTree *DT, AssumptionCache *AC,
585*9880d681SAndroid Build Coastguard Worker                              const Instruction *CxtI) {
586*9880d681SAndroid Build Coastguard Worker   return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
587*9880d681SAndroid Build Coastguard Worker                            RecursionLimit);
588*9880d681SAndroid Build Coastguard Worker }
589*9880d681SAndroid Build Coastguard Worker 
590*9880d681SAndroid Build Coastguard Worker /// \brief Compute the base pointer and cumulative constant offsets for V.
591*9880d681SAndroid Build Coastguard Worker ///
592*9880d681SAndroid Build Coastguard Worker /// This strips all constant offsets off of V, leaving it the base pointer, and
593*9880d681SAndroid Build Coastguard Worker /// accumulates the total constant offset applied in the returned constant. It
594*9880d681SAndroid Build Coastguard Worker /// returns 0 if V is not a pointer, and returns the constant '0' if there are
595*9880d681SAndroid Build Coastguard Worker /// no constant offsets applied.
596*9880d681SAndroid Build Coastguard Worker ///
597*9880d681SAndroid Build Coastguard Worker /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
598*9880d681SAndroid Build Coastguard Worker /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
599*9880d681SAndroid Build Coastguard Worker /// folding.
stripAndComputeConstantOffsets(const DataLayout & DL,Value * & V,bool AllowNonInbounds=false)600*9880d681SAndroid Build Coastguard Worker static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
601*9880d681SAndroid Build Coastguard Worker                                                 bool AllowNonInbounds = false) {
602*9880d681SAndroid Build Coastguard Worker   assert(V->getType()->getScalarType()->isPointerTy());
603*9880d681SAndroid Build Coastguard Worker 
604*9880d681SAndroid Build Coastguard Worker   Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
605*9880d681SAndroid Build Coastguard Worker   APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
606*9880d681SAndroid Build Coastguard Worker 
607*9880d681SAndroid Build Coastguard Worker   // Even though we don't look through PHI nodes, we could be called on an
608*9880d681SAndroid Build Coastguard Worker   // instruction in an unreachable block, which may be on a cycle.
609*9880d681SAndroid Build Coastguard Worker   SmallPtrSet<Value *, 4> Visited;
610*9880d681SAndroid Build Coastguard Worker   Visited.insert(V);
611*9880d681SAndroid Build Coastguard Worker   do {
612*9880d681SAndroid Build Coastguard Worker     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
613*9880d681SAndroid Build Coastguard Worker       if ((!AllowNonInbounds && !GEP->isInBounds()) ||
614*9880d681SAndroid Build Coastguard Worker           !GEP->accumulateConstantOffset(DL, Offset))
615*9880d681SAndroid Build Coastguard Worker         break;
616*9880d681SAndroid Build Coastguard Worker       V = GEP->getPointerOperand();
617*9880d681SAndroid Build Coastguard Worker     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
618*9880d681SAndroid Build Coastguard Worker       V = cast<Operator>(V)->getOperand(0);
619*9880d681SAndroid Build Coastguard Worker     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
620*9880d681SAndroid Build Coastguard Worker       if (GA->isInterposable())
621*9880d681SAndroid Build Coastguard Worker         break;
622*9880d681SAndroid Build Coastguard Worker       V = GA->getAliasee();
623*9880d681SAndroid Build Coastguard Worker     } else {
624*9880d681SAndroid Build Coastguard Worker       if (auto CS = CallSite(V))
625*9880d681SAndroid Build Coastguard Worker         if (Value *RV = CS.getReturnedArgOperand()) {
626*9880d681SAndroid Build Coastguard Worker           V = RV;
627*9880d681SAndroid Build Coastguard Worker           continue;
628*9880d681SAndroid Build Coastguard Worker         }
629*9880d681SAndroid Build Coastguard Worker       break;
630*9880d681SAndroid Build Coastguard Worker     }
631*9880d681SAndroid Build Coastguard Worker     assert(V->getType()->getScalarType()->isPointerTy() &&
632*9880d681SAndroid Build Coastguard Worker            "Unexpected operand type!");
633*9880d681SAndroid Build Coastguard Worker   } while (Visited.insert(V).second);
634*9880d681SAndroid Build Coastguard Worker 
635*9880d681SAndroid Build Coastguard Worker   Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
636*9880d681SAndroid Build Coastguard Worker   if (V->getType()->isVectorTy())
637*9880d681SAndroid Build Coastguard Worker     return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
638*9880d681SAndroid Build Coastguard Worker                                     OffsetIntPtr);
639*9880d681SAndroid Build Coastguard Worker   return OffsetIntPtr;
640*9880d681SAndroid Build Coastguard Worker }
641*9880d681SAndroid Build Coastguard Worker 
642*9880d681SAndroid Build Coastguard Worker /// \brief Compute the constant difference between two pointer values.
643*9880d681SAndroid Build Coastguard Worker /// If the difference is not a constant, returns zero.
computePointerDifference(const DataLayout & DL,Value * LHS,Value * RHS)644*9880d681SAndroid Build Coastguard Worker static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
645*9880d681SAndroid Build Coastguard Worker                                           Value *RHS) {
646*9880d681SAndroid Build Coastguard Worker   Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
647*9880d681SAndroid Build Coastguard Worker   Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
648*9880d681SAndroid Build Coastguard Worker 
649*9880d681SAndroid Build Coastguard Worker   // If LHS and RHS are not related via constant offsets to the same base
650*9880d681SAndroid Build Coastguard Worker   // value, there is nothing we can do here.
651*9880d681SAndroid Build Coastguard Worker   if (LHS != RHS)
652*9880d681SAndroid Build Coastguard Worker     return nullptr;
653*9880d681SAndroid Build Coastguard Worker 
654*9880d681SAndroid Build Coastguard Worker   // Otherwise, the difference of LHS - RHS can be computed as:
655*9880d681SAndroid Build Coastguard Worker   //    LHS - RHS
656*9880d681SAndroid Build Coastguard Worker   //  = (LHSOffset + Base) - (RHSOffset + Base)
657*9880d681SAndroid Build Coastguard Worker   //  = LHSOffset - RHSOffset
658*9880d681SAndroid Build Coastguard Worker   return ConstantExpr::getSub(LHSOffset, RHSOffset);
659*9880d681SAndroid Build Coastguard Worker }
660*9880d681SAndroid Build Coastguard Worker 
661*9880d681SAndroid Build Coastguard Worker /// Given operands for a Sub, see if we can fold the result.
662*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifySubInst(Value * Op0,Value * Op1,bool isNSW,bool isNUW,const Query & Q,unsigned MaxRecurse)663*9880d681SAndroid Build Coastguard Worker static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
664*9880d681SAndroid Build Coastguard Worker                               const Query &Q, unsigned MaxRecurse) {
665*9880d681SAndroid Build Coastguard Worker   if (Constant *CLHS = dyn_cast<Constant>(Op0))
666*9880d681SAndroid Build Coastguard Worker     if (Constant *CRHS = dyn_cast<Constant>(Op1))
667*9880d681SAndroid Build Coastguard Worker       return ConstantFoldBinaryOpOperands(Instruction::Sub, CLHS, CRHS, Q.DL);
668*9880d681SAndroid Build Coastguard Worker 
669*9880d681SAndroid Build Coastguard Worker   // X - undef -> undef
670*9880d681SAndroid Build Coastguard Worker   // undef - X -> undef
671*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
672*9880d681SAndroid Build Coastguard Worker     return UndefValue::get(Op0->getType());
673*9880d681SAndroid Build Coastguard Worker 
674*9880d681SAndroid Build Coastguard Worker   // X - 0 -> X
675*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Zero()))
676*9880d681SAndroid Build Coastguard Worker     return Op0;
677*9880d681SAndroid Build Coastguard Worker 
678*9880d681SAndroid Build Coastguard Worker   // X - X -> 0
679*9880d681SAndroid Build Coastguard Worker   if (Op0 == Op1)
680*9880d681SAndroid Build Coastguard Worker     return Constant::getNullValue(Op0->getType());
681*9880d681SAndroid Build Coastguard Worker 
682*9880d681SAndroid Build Coastguard Worker   // 0 - X -> 0 if the sub is NUW.
683*9880d681SAndroid Build Coastguard Worker   if (isNUW && match(Op0, m_Zero()))
684*9880d681SAndroid Build Coastguard Worker     return Op0;
685*9880d681SAndroid Build Coastguard Worker 
686*9880d681SAndroid Build Coastguard Worker   // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
687*9880d681SAndroid Build Coastguard Worker   // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
688*9880d681SAndroid Build Coastguard Worker   Value *X = nullptr, *Y = nullptr, *Z = Op1;
689*9880d681SAndroid Build Coastguard Worker   if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
690*9880d681SAndroid Build Coastguard Worker     // See if "V === Y - Z" simplifies.
691*9880d681SAndroid Build Coastguard Worker     if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
692*9880d681SAndroid Build Coastguard Worker       // It does!  Now see if "X + V" simplifies.
693*9880d681SAndroid Build Coastguard Worker       if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
694*9880d681SAndroid Build Coastguard Worker         // It does, we successfully reassociated!
695*9880d681SAndroid Build Coastguard Worker         ++NumReassoc;
696*9880d681SAndroid Build Coastguard Worker         return W;
697*9880d681SAndroid Build Coastguard Worker       }
698*9880d681SAndroid Build Coastguard Worker     // See if "V === X - Z" simplifies.
699*9880d681SAndroid Build Coastguard Worker     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
700*9880d681SAndroid Build Coastguard Worker       // It does!  Now see if "Y + V" simplifies.
701*9880d681SAndroid Build Coastguard Worker       if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
702*9880d681SAndroid Build Coastguard Worker         // It does, we successfully reassociated!
703*9880d681SAndroid Build Coastguard Worker         ++NumReassoc;
704*9880d681SAndroid Build Coastguard Worker         return W;
705*9880d681SAndroid Build Coastguard Worker       }
706*9880d681SAndroid Build Coastguard Worker   }
707*9880d681SAndroid Build Coastguard Worker 
708*9880d681SAndroid Build Coastguard Worker   // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
709*9880d681SAndroid Build Coastguard Worker   // For example, X - (X + 1) -> -1
710*9880d681SAndroid Build Coastguard Worker   X = Op0;
711*9880d681SAndroid Build Coastguard Worker   if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
712*9880d681SAndroid Build Coastguard Worker     // See if "V === X - Y" simplifies.
713*9880d681SAndroid Build Coastguard Worker     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
714*9880d681SAndroid Build Coastguard Worker       // It does!  Now see if "V - Z" simplifies.
715*9880d681SAndroid Build Coastguard Worker       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
716*9880d681SAndroid Build Coastguard Worker         // It does, we successfully reassociated!
717*9880d681SAndroid Build Coastguard Worker         ++NumReassoc;
718*9880d681SAndroid Build Coastguard Worker         return W;
719*9880d681SAndroid Build Coastguard Worker       }
720*9880d681SAndroid Build Coastguard Worker     // See if "V === X - Z" simplifies.
721*9880d681SAndroid Build Coastguard Worker     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
722*9880d681SAndroid Build Coastguard Worker       // It does!  Now see if "V - Y" simplifies.
723*9880d681SAndroid Build Coastguard Worker       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
724*9880d681SAndroid Build Coastguard Worker         // It does, we successfully reassociated!
725*9880d681SAndroid Build Coastguard Worker         ++NumReassoc;
726*9880d681SAndroid Build Coastguard Worker         return W;
727*9880d681SAndroid Build Coastguard Worker       }
728*9880d681SAndroid Build Coastguard Worker   }
729*9880d681SAndroid Build Coastguard Worker 
730*9880d681SAndroid Build Coastguard Worker   // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
731*9880d681SAndroid Build Coastguard Worker   // For example, X - (X - Y) -> Y.
732*9880d681SAndroid Build Coastguard Worker   Z = Op0;
733*9880d681SAndroid Build Coastguard Worker   if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
734*9880d681SAndroid Build Coastguard Worker     // See if "V === Z - X" simplifies.
735*9880d681SAndroid Build Coastguard Worker     if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
736*9880d681SAndroid Build Coastguard Worker       // It does!  Now see if "V + Y" simplifies.
737*9880d681SAndroid Build Coastguard Worker       if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
738*9880d681SAndroid Build Coastguard Worker         // It does, we successfully reassociated!
739*9880d681SAndroid Build Coastguard Worker         ++NumReassoc;
740*9880d681SAndroid Build Coastguard Worker         return W;
741*9880d681SAndroid Build Coastguard Worker       }
742*9880d681SAndroid Build Coastguard Worker 
743*9880d681SAndroid Build Coastguard Worker   // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
744*9880d681SAndroid Build Coastguard Worker   if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
745*9880d681SAndroid Build Coastguard Worker       match(Op1, m_Trunc(m_Value(Y))))
746*9880d681SAndroid Build Coastguard Worker     if (X->getType() == Y->getType())
747*9880d681SAndroid Build Coastguard Worker       // See if "V === X - Y" simplifies.
748*9880d681SAndroid Build Coastguard Worker       if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
749*9880d681SAndroid Build Coastguard Worker         // It does!  Now see if "trunc V" simplifies.
750*9880d681SAndroid Build Coastguard Worker         if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
751*9880d681SAndroid Build Coastguard Worker           // It does, return the simplified "trunc V".
752*9880d681SAndroid Build Coastguard Worker           return W;
753*9880d681SAndroid Build Coastguard Worker 
754*9880d681SAndroid Build Coastguard Worker   // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
755*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_PtrToInt(m_Value(X))) &&
756*9880d681SAndroid Build Coastguard Worker       match(Op1, m_PtrToInt(m_Value(Y))))
757*9880d681SAndroid Build Coastguard Worker     if (Constant *Result = computePointerDifference(Q.DL, X, Y))
758*9880d681SAndroid Build Coastguard Worker       return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
759*9880d681SAndroid Build Coastguard Worker 
760*9880d681SAndroid Build Coastguard Worker   // i1 sub -> xor.
761*9880d681SAndroid Build Coastguard Worker   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
762*9880d681SAndroid Build Coastguard Worker     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
763*9880d681SAndroid Build Coastguard Worker       return V;
764*9880d681SAndroid Build Coastguard Worker 
765*9880d681SAndroid Build Coastguard Worker   // Threading Sub over selects and phi nodes is pointless, so don't bother.
766*9880d681SAndroid Build Coastguard Worker   // Threading over the select in "A - select(cond, B, C)" means evaluating
767*9880d681SAndroid Build Coastguard Worker   // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
768*9880d681SAndroid Build Coastguard Worker   // only if B and C are equal.  If B and C are equal then (since we assume
769*9880d681SAndroid Build Coastguard Worker   // that operands have already been simplified) "select(cond, B, C)" should
770*9880d681SAndroid Build Coastguard Worker   // have been simplified to the common value of B and C already.  Analysing
771*9880d681SAndroid Build Coastguard Worker   // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
772*9880d681SAndroid Build Coastguard Worker   // for threading over phi nodes.
773*9880d681SAndroid Build Coastguard Worker 
774*9880d681SAndroid Build Coastguard Worker   return nullptr;
775*9880d681SAndroid Build Coastguard Worker }
776*9880d681SAndroid Build Coastguard Worker 
SimplifySubInst(Value * Op0,Value * Op1,bool isNSW,bool isNUW,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)777*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
778*9880d681SAndroid Build Coastguard Worker                              const DataLayout &DL, const TargetLibraryInfo *TLI,
779*9880d681SAndroid Build Coastguard Worker                              const DominatorTree *DT, AssumptionCache *AC,
780*9880d681SAndroid Build Coastguard Worker                              const Instruction *CxtI) {
781*9880d681SAndroid Build Coastguard Worker   return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
782*9880d681SAndroid Build Coastguard Worker                            RecursionLimit);
783*9880d681SAndroid Build Coastguard Worker }
784*9880d681SAndroid Build Coastguard Worker 
785*9880d681SAndroid Build Coastguard Worker /// Given operands for an FAdd, see if we can fold the result.  If not, this
786*9880d681SAndroid Build Coastguard Worker /// returns null.
SimplifyFAddInst(Value * Op0,Value * Op1,FastMathFlags FMF,const Query & Q,unsigned MaxRecurse)787*9880d681SAndroid Build Coastguard Worker static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
788*9880d681SAndroid Build Coastguard Worker                               const Query &Q, unsigned MaxRecurse) {
789*9880d681SAndroid Build Coastguard Worker   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
790*9880d681SAndroid Build Coastguard Worker     if (Constant *CRHS = dyn_cast<Constant>(Op1))
791*9880d681SAndroid Build Coastguard Worker       return ConstantFoldBinaryOpOperands(Instruction::FAdd, CLHS, CRHS, Q.DL);
792*9880d681SAndroid Build Coastguard Worker 
793*9880d681SAndroid Build Coastguard Worker     // Canonicalize the constant to the RHS.
794*9880d681SAndroid Build Coastguard Worker     std::swap(Op0, Op1);
795*9880d681SAndroid Build Coastguard Worker   }
796*9880d681SAndroid Build Coastguard Worker 
797*9880d681SAndroid Build Coastguard Worker   // fadd X, -0 ==> X
798*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_NegZero()))
799*9880d681SAndroid Build Coastguard Worker     return Op0;
800*9880d681SAndroid Build Coastguard Worker 
801*9880d681SAndroid Build Coastguard Worker   // fadd X, 0 ==> X, when we know X is not -0
802*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Zero()) &&
803*9880d681SAndroid Build Coastguard Worker       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
804*9880d681SAndroid Build Coastguard Worker     return Op0;
805*9880d681SAndroid Build Coastguard Worker 
806*9880d681SAndroid Build Coastguard Worker   // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
807*9880d681SAndroid Build Coastguard Worker   //   where nnan and ninf have to occur at least once somewhere in this
808*9880d681SAndroid Build Coastguard Worker   //   expression
809*9880d681SAndroid Build Coastguard Worker   Value *SubOp = nullptr;
810*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
811*9880d681SAndroid Build Coastguard Worker     SubOp = Op1;
812*9880d681SAndroid Build Coastguard Worker   else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
813*9880d681SAndroid Build Coastguard Worker     SubOp = Op0;
814*9880d681SAndroid Build Coastguard Worker   if (SubOp) {
815*9880d681SAndroid Build Coastguard Worker     Instruction *FSub = cast<Instruction>(SubOp);
816*9880d681SAndroid Build Coastguard Worker     if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
817*9880d681SAndroid Build Coastguard Worker         (FMF.noInfs() || FSub->hasNoInfs()))
818*9880d681SAndroid Build Coastguard Worker       return Constant::getNullValue(Op0->getType());
819*9880d681SAndroid Build Coastguard Worker   }
820*9880d681SAndroid Build Coastguard Worker 
821*9880d681SAndroid Build Coastguard Worker   return nullptr;
822*9880d681SAndroid Build Coastguard Worker }
823*9880d681SAndroid Build Coastguard Worker 
824*9880d681SAndroid Build Coastguard Worker /// Given operands for an FSub, see if we can fold the result.  If not, this
825*9880d681SAndroid Build Coastguard Worker /// returns null.
SimplifyFSubInst(Value * Op0,Value * Op1,FastMathFlags FMF,const Query & Q,unsigned MaxRecurse)826*9880d681SAndroid Build Coastguard Worker static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
827*9880d681SAndroid Build Coastguard Worker                               const Query &Q, unsigned MaxRecurse) {
828*9880d681SAndroid Build Coastguard Worker   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
829*9880d681SAndroid Build Coastguard Worker     if (Constant *CRHS = dyn_cast<Constant>(Op1))
830*9880d681SAndroid Build Coastguard Worker       return ConstantFoldBinaryOpOperands(Instruction::FSub, CLHS, CRHS, Q.DL);
831*9880d681SAndroid Build Coastguard Worker   }
832*9880d681SAndroid Build Coastguard Worker 
833*9880d681SAndroid Build Coastguard Worker   // fsub X, 0 ==> X
834*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Zero()))
835*9880d681SAndroid Build Coastguard Worker     return Op0;
836*9880d681SAndroid Build Coastguard Worker 
837*9880d681SAndroid Build Coastguard Worker   // fsub X, -0 ==> X, when we know X is not -0
838*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_NegZero()) &&
839*9880d681SAndroid Build Coastguard Worker       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
840*9880d681SAndroid Build Coastguard Worker     return Op0;
841*9880d681SAndroid Build Coastguard Worker 
842*9880d681SAndroid Build Coastguard Worker   // fsub -0.0, (fsub -0.0, X) ==> X
843*9880d681SAndroid Build Coastguard Worker   Value *X;
844*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_NegZero()) && match(Op1, m_FSub(m_NegZero(), m_Value(X))))
845*9880d681SAndroid Build Coastguard Worker     return X;
846*9880d681SAndroid Build Coastguard Worker 
847*9880d681SAndroid Build Coastguard Worker   // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
848*9880d681SAndroid Build Coastguard Worker   if (FMF.noSignedZeros() && match(Op0, m_AnyZero()) &&
849*9880d681SAndroid Build Coastguard Worker       match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
850*9880d681SAndroid Build Coastguard Worker     return X;
851*9880d681SAndroid Build Coastguard Worker 
852*9880d681SAndroid Build Coastguard Worker   // fsub nnan x, x ==> 0.0
853*9880d681SAndroid Build Coastguard Worker   if (FMF.noNaNs() && Op0 == Op1)
854*9880d681SAndroid Build Coastguard Worker     return Constant::getNullValue(Op0->getType());
855*9880d681SAndroid Build Coastguard Worker 
856*9880d681SAndroid Build Coastguard Worker   return nullptr;
857*9880d681SAndroid Build Coastguard Worker }
858*9880d681SAndroid Build Coastguard Worker 
859*9880d681SAndroid Build Coastguard Worker /// Given the operands for an FMul, see if we can fold the result
SimplifyFMulInst(Value * Op0,Value * Op1,FastMathFlags FMF,const Query & Q,unsigned MaxRecurse)860*9880d681SAndroid Build Coastguard Worker static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
861*9880d681SAndroid Build Coastguard Worker                                FastMathFlags FMF,
862*9880d681SAndroid Build Coastguard Worker                                const Query &Q,
863*9880d681SAndroid Build Coastguard Worker                                unsigned MaxRecurse) {
864*9880d681SAndroid Build Coastguard Worker  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
865*9880d681SAndroid Build Coastguard Worker     if (Constant *CRHS = dyn_cast<Constant>(Op1))
866*9880d681SAndroid Build Coastguard Worker       return ConstantFoldBinaryOpOperands(Instruction::FMul, CLHS, CRHS, Q.DL);
867*9880d681SAndroid Build Coastguard Worker 
868*9880d681SAndroid Build Coastguard Worker     // Canonicalize the constant to the RHS.
869*9880d681SAndroid Build Coastguard Worker     std::swap(Op0, Op1);
870*9880d681SAndroid Build Coastguard Worker  }
871*9880d681SAndroid Build Coastguard Worker 
872*9880d681SAndroid Build Coastguard Worker  // fmul X, 1.0 ==> X
873*9880d681SAndroid Build Coastguard Worker  if (match(Op1, m_FPOne()))
874*9880d681SAndroid Build Coastguard Worker    return Op0;
875*9880d681SAndroid Build Coastguard Worker 
876*9880d681SAndroid Build Coastguard Worker  // fmul nnan nsz X, 0 ==> 0
877*9880d681SAndroid Build Coastguard Worker  if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
878*9880d681SAndroid Build Coastguard Worker    return Op1;
879*9880d681SAndroid Build Coastguard Worker 
880*9880d681SAndroid Build Coastguard Worker  return nullptr;
881*9880d681SAndroid Build Coastguard Worker }
882*9880d681SAndroid Build Coastguard Worker 
883*9880d681SAndroid Build Coastguard Worker /// Given operands for a Mul, see if we can fold the result.
884*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifyMulInst(Value * Op0,Value * Op1,const Query & Q,unsigned MaxRecurse)885*9880d681SAndroid Build Coastguard Worker static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
886*9880d681SAndroid Build Coastguard Worker                               unsigned MaxRecurse) {
887*9880d681SAndroid Build Coastguard Worker   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
888*9880d681SAndroid Build Coastguard Worker     if (Constant *CRHS = dyn_cast<Constant>(Op1))
889*9880d681SAndroid Build Coastguard Worker       return ConstantFoldBinaryOpOperands(Instruction::Mul, CLHS, CRHS, Q.DL);
890*9880d681SAndroid Build Coastguard Worker 
891*9880d681SAndroid Build Coastguard Worker     // Canonicalize the constant to the RHS.
892*9880d681SAndroid Build Coastguard Worker     std::swap(Op0, Op1);
893*9880d681SAndroid Build Coastguard Worker   }
894*9880d681SAndroid Build Coastguard Worker 
895*9880d681SAndroid Build Coastguard Worker   // X * undef -> 0
896*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Undef()))
897*9880d681SAndroid Build Coastguard Worker     return Constant::getNullValue(Op0->getType());
898*9880d681SAndroid Build Coastguard Worker 
899*9880d681SAndroid Build Coastguard Worker   // X * 0 -> 0
900*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Zero()))
901*9880d681SAndroid Build Coastguard Worker     return Op1;
902*9880d681SAndroid Build Coastguard Worker 
903*9880d681SAndroid Build Coastguard Worker   // X * 1 -> X
904*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_One()))
905*9880d681SAndroid Build Coastguard Worker     return Op0;
906*9880d681SAndroid Build Coastguard Worker 
907*9880d681SAndroid Build Coastguard Worker   // (X / Y) * Y -> X if the division is exact.
908*9880d681SAndroid Build Coastguard Worker   Value *X = nullptr;
909*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
910*9880d681SAndroid Build Coastguard Worker       match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))   // Y * (X / Y)
911*9880d681SAndroid Build Coastguard Worker     return X;
912*9880d681SAndroid Build Coastguard Worker 
913*9880d681SAndroid Build Coastguard Worker   // i1 mul -> and.
914*9880d681SAndroid Build Coastguard Worker   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
915*9880d681SAndroid Build Coastguard Worker     if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
916*9880d681SAndroid Build Coastguard Worker       return V;
917*9880d681SAndroid Build Coastguard Worker 
918*9880d681SAndroid Build Coastguard Worker   // Try some generic simplifications for associative operations.
919*9880d681SAndroid Build Coastguard Worker   if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
920*9880d681SAndroid Build Coastguard Worker                                           MaxRecurse))
921*9880d681SAndroid Build Coastguard Worker     return V;
922*9880d681SAndroid Build Coastguard Worker 
923*9880d681SAndroid Build Coastguard Worker   // Mul distributes over Add.  Try some generic simplifications based on this.
924*9880d681SAndroid Build Coastguard Worker   if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
925*9880d681SAndroid Build Coastguard Worker                              Q, MaxRecurse))
926*9880d681SAndroid Build Coastguard Worker     return V;
927*9880d681SAndroid Build Coastguard Worker 
928*9880d681SAndroid Build Coastguard Worker   // If the operation is with the result of a select instruction, check whether
929*9880d681SAndroid Build Coastguard Worker   // operating on either branch of the select always yields the same value.
930*9880d681SAndroid Build Coastguard Worker   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
931*9880d681SAndroid Build Coastguard Worker     if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
932*9880d681SAndroid Build Coastguard Worker                                          MaxRecurse))
933*9880d681SAndroid Build Coastguard Worker       return V;
934*9880d681SAndroid Build Coastguard Worker 
935*9880d681SAndroid Build Coastguard Worker   // If the operation is with the result of a phi instruction, check whether
936*9880d681SAndroid Build Coastguard Worker   // operating on all incoming values of the phi always yields the same value.
937*9880d681SAndroid Build Coastguard Worker   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
938*9880d681SAndroid Build Coastguard Worker     if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
939*9880d681SAndroid Build Coastguard Worker                                       MaxRecurse))
940*9880d681SAndroid Build Coastguard Worker       return V;
941*9880d681SAndroid Build Coastguard Worker 
942*9880d681SAndroid Build Coastguard Worker   return nullptr;
943*9880d681SAndroid Build Coastguard Worker }
944*9880d681SAndroid Build Coastguard Worker 
SimplifyFAddInst(Value * Op0,Value * Op1,FastMathFlags FMF,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)945*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
946*9880d681SAndroid Build Coastguard Worker                               const DataLayout &DL,
947*9880d681SAndroid Build Coastguard Worker                               const TargetLibraryInfo *TLI,
948*9880d681SAndroid Build Coastguard Worker                               const DominatorTree *DT, AssumptionCache *AC,
949*9880d681SAndroid Build Coastguard Worker                               const Instruction *CxtI) {
950*9880d681SAndroid Build Coastguard Worker   return ::SimplifyFAddInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
951*9880d681SAndroid Build Coastguard Worker                             RecursionLimit);
952*9880d681SAndroid Build Coastguard Worker }
953*9880d681SAndroid Build Coastguard Worker 
SimplifyFSubInst(Value * Op0,Value * Op1,FastMathFlags FMF,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)954*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
955*9880d681SAndroid Build Coastguard Worker                               const DataLayout &DL,
956*9880d681SAndroid Build Coastguard Worker                               const TargetLibraryInfo *TLI,
957*9880d681SAndroid Build Coastguard Worker                               const DominatorTree *DT, AssumptionCache *AC,
958*9880d681SAndroid Build Coastguard Worker                               const Instruction *CxtI) {
959*9880d681SAndroid Build Coastguard Worker   return ::SimplifyFSubInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
960*9880d681SAndroid Build Coastguard Worker                             RecursionLimit);
961*9880d681SAndroid Build Coastguard Worker }
962*9880d681SAndroid Build Coastguard Worker 
SimplifyFMulInst(Value * Op0,Value * Op1,FastMathFlags FMF,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)963*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
964*9880d681SAndroid Build Coastguard Worker                               const DataLayout &DL,
965*9880d681SAndroid Build Coastguard Worker                               const TargetLibraryInfo *TLI,
966*9880d681SAndroid Build Coastguard Worker                               const DominatorTree *DT, AssumptionCache *AC,
967*9880d681SAndroid Build Coastguard Worker                               const Instruction *CxtI) {
968*9880d681SAndroid Build Coastguard Worker   return ::SimplifyFMulInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
969*9880d681SAndroid Build Coastguard Worker                             RecursionLimit);
970*9880d681SAndroid Build Coastguard Worker }
971*9880d681SAndroid Build Coastguard Worker 
SimplifyMulInst(Value * Op0,Value * Op1,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)972*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout &DL,
973*9880d681SAndroid Build Coastguard Worker                              const TargetLibraryInfo *TLI,
974*9880d681SAndroid Build Coastguard Worker                              const DominatorTree *DT, AssumptionCache *AC,
975*9880d681SAndroid Build Coastguard Worker                              const Instruction *CxtI) {
976*9880d681SAndroid Build Coastguard Worker   return ::SimplifyMulInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
977*9880d681SAndroid Build Coastguard Worker                            RecursionLimit);
978*9880d681SAndroid Build Coastguard Worker }
979*9880d681SAndroid Build Coastguard Worker 
980*9880d681SAndroid Build Coastguard Worker /// Given operands for an SDiv or UDiv, see if we can fold the result.
981*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifyDiv(Instruction::BinaryOps Opcode,Value * Op0,Value * Op1,const Query & Q,unsigned MaxRecurse)982*9880d681SAndroid Build Coastguard Worker static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
983*9880d681SAndroid Build Coastguard Worker                           const Query &Q, unsigned MaxRecurse) {
984*9880d681SAndroid Build Coastguard Worker   if (Constant *C0 = dyn_cast<Constant>(Op0))
985*9880d681SAndroid Build Coastguard Worker     if (Constant *C1 = dyn_cast<Constant>(Op1))
986*9880d681SAndroid Build Coastguard Worker       return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
987*9880d681SAndroid Build Coastguard Worker 
988*9880d681SAndroid Build Coastguard Worker   bool isSigned = Opcode == Instruction::SDiv;
989*9880d681SAndroid Build Coastguard Worker 
990*9880d681SAndroid Build Coastguard Worker   // X / undef -> undef
991*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Undef()))
992*9880d681SAndroid Build Coastguard Worker     return Op1;
993*9880d681SAndroid Build Coastguard Worker 
994*9880d681SAndroid Build Coastguard Worker   // X / 0 -> undef, we don't need to preserve faults!
995*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Zero()))
996*9880d681SAndroid Build Coastguard Worker     return UndefValue::get(Op1->getType());
997*9880d681SAndroid Build Coastguard Worker 
998*9880d681SAndroid Build Coastguard Worker   // undef / X -> 0
999*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_Undef()))
1000*9880d681SAndroid Build Coastguard Worker     return Constant::getNullValue(Op0->getType());
1001*9880d681SAndroid Build Coastguard Worker 
1002*9880d681SAndroid Build Coastguard Worker   // 0 / X -> 0, we don't need to preserve faults!
1003*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_Zero()))
1004*9880d681SAndroid Build Coastguard Worker     return Op0;
1005*9880d681SAndroid Build Coastguard Worker 
1006*9880d681SAndroid Build Coastguard Worker   // X / 1 -> X
1007*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_One()))
1008*9880d681SAndroid Build Coastguard Worker     return Op0;
1009*9880d681SAndroid Build Coastguard Worker 
1010*9880d681SAndroid Build Coastguard Worker   if (Op0->getType()->isIntegerTy(1))
1011*9880d681SAndroid Build Coastguard Worker     // It can't be division by zero, hence it must be division by one.
1012*9880d681SAndroid Build Coastguard Worker     return Op0;
1013*9880d681SAndroid Build Coastguard Worker 
1014*9880d681SAndroid Build Coastguard Worker   // X / X -> 1
1015*9880d681SAndroid Build Coastguard Worker   if (Op0 == Op1)
1016*9880d681SAndroid Build Coastguard Worker     return ConstantInt::get(Op0->getType(), 1);
1017*9880d681SAndroid Build Coastguard Worker 
1018*9880d681SAndroid Build Coastguard Worker   // (X * Y) / Y -> X if the multiplication does not overflow.
1019*9880d681SAndroid Build Coastguard Worker   Value *X = nullptr, *Y = nullptr;
1020*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1021*9880d681SAndroid Build Coastguard Worker     if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
1022*9880d681SAndroid Build Coastguard Worker     OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
1023*9880d681SAndroid Build Coastguard Worker     // If the Mul knows it does not overflow, then we are good to go.
1024*9880d681SAndroid Build Coastguard Worker     if ((isSigned && Mul->hasNoSignedWrap()) ||
1025*9880d681SAndroid Build Coastguard Worker         (!isSigned && Mul->hasNoUnsignedWrap()))
1026*9880d681SAndroid Build Coastguard Worker       return X;
1027*9880d681SAndroid Build Coastguard Worker     // If X has the form X = A / Y then X * Y cannot overflow.
1028*9880d681SAndroid Build Coastguard Worker     if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1029*9880d681SAndroid Build Coastguard Worker       if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1030*9880d681SAndroid Build Coastguard Worker         return X;
1031*9880d681SAndroid Build Coastguard Worker   }
1032*9880d681SAndroid Build Coastguard Worker 
1033*9880d681SAndroid Build Coastguard Worker   // (X rem Y) / Y -> 0
1034*9880d681SAndroid Build Coastguard Worker   if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1035*9880d681SAndroid Build Coastguard Worker       (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1036*9880d681SAndroid Build Coastguard Worker     return Constant::getNullValue(Op0->getType());
1037*9880d681SAndroid Build Coastguard Worker 
1038*9880d681SAndroid Build Coastguard Worker   // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1039*9880d681SAndroid Build Coastguard Worker   ConstantInt *C1, *C2;
1040*9880d681SAndroid Build Coastguard Worker   if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1041*9880d681SAndroid Build Coastguard Worker       match(Op1, m_ConstantInt(C2))) {
1042*9880d681SAndroid Build Coastguard Worker     bool Overflow;
1043*9880d681SAndroid Build Coastguard Worker     C1->getValue().umul_ov(C2->getValue(), Overflow);
1044*9880d681SAndroid Build Coastguard Worker     if (Overflow)
1045*9880d681SAndroid Build Coastguard Worker       return Constant::getNullValue(Op0->getType());
1046*9880d681SAndroid Build Coastguard Worker   }
1047*9880d681SAndroid Build Coastguard Worker 
1048*9880d681SAndroid Build Coastguard Worker   // If the operation is with the result of a select instruction, check whether
1049*9880d681SAndroid Build Coastguard Worker   // operating on either branch of the select always yields the same value.
1050*9880d681SAndroid Build Coastguard Worker   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1051*9880d681SAndroid Build Coastguard Worker     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1052*9880d681SAndroid Build Coastguard Worker       return V;
1053*9880d681SAndroid Build Coastguard Worker 
1054*9880d681SAndroid Build Coastguard Worker   // If the operation is with the result of a phi instruction, check whether
1055*9880d681SAndroid Build Coastguard Worker   // operating on all incoming values of the phi always yields the same value.
1056*9880d681SAndroid Build Coastguard Worker   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1057*9880d681SAndroid Build Coastguard Worker     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1058*9880d681SAndroid Build Coastguard Worker       return V;
1059*9880d681SAndroid Build Coastguard Worker 
1060*9880d681SAndroid Build Coastguard Worker   return nullptr;
1061*9880d681SAndroid Build Coastguard Worker }
1062*9880d681SAndroid Build Coastguard Worker 
1063*9880d681SAndroid Build Coastguard Worker /// Given operands for an SDiv, see if we can fold the result.
1064*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifySDivInst(Value * Op0,Value * Op1,const Query & Q,unsigned MaxRecurse)1065*9880d681SAndroid Build Coastguard Worker static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1066*9880d681SAndroid Build Coastguard Worker                                unsigned MaxRecurse) {
1067*9880d681SAndroid Build Coastguard Worker   if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
1068*9880d681SAndroid Build Coastguard Worker     return V;
1069*9880d681SAndroid Build Coastguard Worker 
1070*9880d681SAndroid Build Coastguard Worker   return nullptr;
1071*9880d681SAndroid Build Coastguard Worker }
1072*9880d681SAndroid Build Coastguard Worker 
SimplifySDivInst(Value * Op0,Value * Op1,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)1073*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
1074*9880d681SAndroid Build Coastguard Worker                               const TargetLibraryInfo *TLI,
1075*9880d681SAndroid Build Coastguard Worker                               const DominatorTree *DT, AssumptionCache *AC,
1076*9880d681SAndroid Build Coastguard Worker                               const Instruction *CxtI) {
1077*9880d681SAndroid Build Coastguard Worker   return ::SimplifySDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1078*9880d681SAndroid Build Coastguard Worker                             RecursionLimit);
1079*9880d681SAndroid Build Coastguard Worker }
1080*9880d681SAndroid Build Coastguard Worker 
1081*9880d681SAndroid Build Coastguard Worker /// Given operands for a UDiv, see if we can fold the result.
1082*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifyUDivInst(Value * Op0,Value * Op1,const Query & Q,unsigned MaxRecurse)1083*9880d681SAndroid Build Coastguard Worker static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1084*9880d681SAndroid Build Coastguard Worker                                unsigned MaxRecurse) {
1085*9880d681SAndroid Build Coastguard Worker   if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
1086*9880d681SAndroid Build Coastguard Worker     return V;
1087*9880d681SAndroid Build Coastguard Worker 
1088*9880d681SAndroid Build Coastguard Worker   return nullptr;
1089*9880d681SAndroid Build Coastguard Worker }
1090*9880d681SAndroid Build Coastguard Worker 
SimplifyUDivInst(Value * Op0,Value * Op1,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)1091*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
1092*9880d681SAndroid Build Coastguard Worker                               const TargetLibraryInfo *TLI,
1093*9880d681SAndroid Build Coastguard Worker                               const DominatorTree *DT, AssumptionCache *AC,
1094*9880d681SAndroid Build Coastguard Worker                               const Instruction *CxtI) {
1095*9880d681SAndroid Build Coastguard Worker   return ::SimplifyUDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1096*9880d681SAndroid Build Coastguard Worker                             RecursionLimit);
1097*9880d681SAndroid Build Coastguard Worker }
1098*9880d681SAndroid Build Coastguard Worker 
SimplifyFDivInst(Value * Op0,Value * Op1,FastMathFlags FMF,const Query & Q,unsigned)1099*9880d681SAndroid Build Coastguard Worker static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1100*9880d681SAndroid Build Coastguard Worker                                const Query &Q, unsigned) {
1101*9880d681SAndroid Build Coastguard Worker   // undef / X -> undef    (the undef could be a snan).
1102*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_Undef()))
1103*9880d681SAndroid Build Coastguard Worker     return Op0;
1104*9880d681SAndroid Build Coastguard Worker 
1105*9880d681SAndroid Build Coastguard Worker   // X / undef -> undef
1106*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Undef()))
1107*9880d681SAndroid Build Coastguard Worker     return Op1;
1108*9880d681SAndroid Build Coastguard Worker 
1109*9880d681SAndroid Build Coastguard Worker   // 0 / X -> 0
1110*9880d681SAndroid Build Coastguard Worker   // Requires that NaNs are off (X could be zero) and signed zeroes are
1111*9880d681SAndroid Build Coastguard Worker   // ignored (X could be positive or negative, so the output sign is unknown).
1112*9880d681SAndroid Build Coastguard Worker   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1113*9880d681SAndroid Build Coastguard Worker     return Op0;
1114*9880d681SAndroid Build Coastguard Worker 
1115*9880d681SAndroid Build Coastguard Worker   if (FMF.noNaNs()) {
1116*9880d681SAndroid Build Coastguard Worker     // X / X -> 1.0 is legal when NaNs are ignored.
1117*9880d681SAndroid Build Coastguard Worker     if (Op0 == Op1)
1118*9880d681SAndroid Build Coastguard Worker       return ConstantFP::get(Op0->getType(), 1.0);
1119*9880d681SAndroid Build Coastguard Worker 
1120*9880d681SAndroid Build Coastguard Worker     // -X /  X -> -1.0 and
1121*9880d681SAndroid Build Coastguard Worker     //  X / -X -> -1.0 are legal when NaNs are ignored.
1122*9880d681SAndroid Build Coastguard Worker     // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
1123*9880d681SAndroid Build Coastguard Worker     if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
1124*9880d681SAndroid Build Coastguard Worker          BinaryOperator::getFNegArgument(Op0) == Op1) ||
1125*9880d681SAndroid Build Coastguard Worker         (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
1126*9880d681SAndroid Build Coastguard Worker          BinaryOperator::getFNegArgument(Op1) == Op0))
1127*9880d681SAndroid Build Coastguard Worker       return ConstantFP::get(Op0->getType(), -1.0);
1128*9880d681SAndroid Build Coastguard Worker   }
1129*9880d681SAndroid Build Coastguard Worker 
1130*9880d681SAndroid Build Coastguard Worker   return nullptr;
1131*9880d681SAndroid Build Coastguard Worker }
1132*9880d681SAndroid Build Coastguard Worker 
SimplifyFDivInst(Value * Op0,Value * Op1,FastMathFlags FMF,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)1133*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1134*9880d681SAndroid Build Coastguard Worker                               const DataLayout &DL,
1135*9880d681SAndroid Build Coastguard Worker                               const TargetLibraryInfo *TLI,
1136*9880d681SAndroid Build Coastguard Worker                               const DominatorTree *DT, AssumptionCache *AC,
1137*9880d681SAndroid Build Coastguard Worker                               const Instruction *CxtI) {
1138*9880d681SAndroid Build Coastguard Worker   return ::SimplifyFDivInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
1139*9880d681SAndroid Build Coastguard Worker                             RecursionLimit);
1140*9880d681SAndroid Build Coastguard Worker }
1141*9880d681SAndroid Build Coastguard Worker 
1142*9880d681SAndroid Build Coastguard Worker /// Given operands for an SRem or URem, see if we can fold the result.
1143*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifyRem(Instruction::BinaryOps Opcode,Value * Op0,Value * Op1,const Query & Q,unsigned MaxRecurse)1144*9880d681SAndroid Build Coastguard Worker static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1145*9880d681SAndroid Build Coastguard Worker                           const Query &Q, unsigned MaxRecurse) {
1146*9880d681SAndroid Build Coastguard Worker   if (Constant *C0 = dyn_cast<Constant>(Op0))
1147*9880d681SAndroid Build Coastguard Worker     if (Constant *C1 = dyn_cast<Constant>(Op1))
1148*9880d681SAndroid Build Coastguard Worker       return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
1149*9880d681SAndroid Build Coastguard Worker 
1150*9880d681SAndroid Build Coastguard Worker   // X % undef -> undef
1151*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Undef()))
1152*9880d681SAndroid Build Coastguard Worker     return Op1;
1153*9880d681SAndroid Build Coastguard Worker 
1154*9880d681SAndroid Build Coastguard Worker   // undef % X -> 0
1155*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_Undef()))
1156*9880d681SAndroid Build Coastguard Worker     return Constant::getNullValue(Op0->getType());
1157*9880d681SAndroid Build Coastguard Worker 
1158*9880d681SAndroid Build Coastguard Worker   // 0 % X -> 0, we don't need to preserve faults!
1159*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_Zero()))
1160*9880d681SAndroid Build Coastguard Worker     return Op0;
1161*9880d681SAndroid Build Coastguard Worker 
1162*9880d681SAndroid Build Coastguard Worker   // X % 0 -> undef, we don't need to preserve faults!
1163*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Zero()))
1164*9880d681SAndroid Build Coastguard Worker     return UndefValue::get(Op0->getType());
1165*9880d681SAndroid Build Coastguard Worker 
1166*9880d681SAndroid Build Coastguard Worker   // X % 1 -> 0
1167*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_One()))
1168*9880d681SAndroid Build Coastguard Worker     return Constant::getNullValue(Op0->getType());
1169*9880d681SAndroid Build Coastguard Worker 
1170*9880d681SAndroid Build Coastguard Worker   if (Op0->getType()->isIntegerTy(1))
1171*9880d681SAndroid Build Coastguard Worker     // It can't be remainder by zero, hence it must be remainder by one.
1172*9880d681SAndroid Build Coastguard Worker     return Constant::getNullValue(Op0->getType());
1173*9880d681SAndroid Build Coastguard Worker 
1174*9880d681SAndroid Build Coastguard Worker   // X % X -> 0
1175*9880d681SAndroid Build Coastguard Worker   if (Op0 == Op1)
1176*9880d681SAndroid Build Coastguard Worker     return Constant::getNullValue(Op0->getType());
1177*9880d681SAndroid Build Coastguard Worker 
1178*9880d681SAndroid Build Coastguard Worker   // (X % Y) % Y -> X % Y
1179*9880d681SAndroid Build Coastguard Worker   if ((Opcode == Instruction::SRem &&
1180*9880d681SAndroid Build Coastguard Worker        match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1181*9880d681SAndroid Build Coastguard Worker       (Opcode == Instruction::URem &&
1182*9880d681SAndroid Build Coastguard Worker        match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1183*9880d681SAndroid Build Coastguard Worker     return Op0;
1184*9880d681SAndroid Build Coastguard Worker 
1185*9880d681SAndroid Build Coastguard Worker   // If the operation is with the result of a select instruction, check whether
1186*9880d681SAndroid Build Coastguard Worker   // operating on either branch of the select always yields the same value.
1187*9880d681SAndroid Build Coastguard Worker   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1188*9880d681SAndroid Build Coastguard Worker     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1189*9880d681SAndroid Build Coastguard Worker       return V;
1190*9880d681SAndroid Build Coastguard Worker 
1191*9880d681SAndroid Build Coastguard Worker   // If the operation is with the result of a phi instruction, check whether
1192*9880d681SAndroid Build Coastguard Worker   // operating on all incoming values of the phi always yields the same value.
1193*9880d681SAndroid Build Coastguard Worker   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1194*9880d681SAndroid Build Coastguard Worker     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1195*9880d681SAndroid Build Coastguard Worker       return V;
1196*9880d681SAndroid Build Coastguard Worker 
1197*9880d681SAndroid Build Coastguard Worker   return nullptr;
1198*9880d681SAndroid Build Coastguard Worker }
1199*9880d681SAndroid Build Coastguard Worker 
1200*9880d681SAndroid Build Coastguard Worker /// Given operands for an SRem, see if we can fold the result.
1201*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifySRemInst(Value * Op0,Value * Op1,const Query & Q,unsigned MaxRecurse)1202*9880d681SAndroid Build Coastguard Worker static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1203*9880d681SAndroid Build Coastguard Worker                                unsigned MaxRecurse) {
1204*9880d681SAndroid Build Coastguard Worker   if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
1205*9880d681SAndroid Build Coastguard Worker     return V;
1206*9880d681SAndroid Build Coastguard Worker 
1207*9880d681SAndroid Build Coastguard Worker   return nullptr;
1208*9880d681SAndroid Build Coastguard Worker }
1209*9880d681SAndroid Build Coastguard Worker 
SimplifySRemInst(Value * Op0,Value * Op1,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)1210*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout &DL,
1211*9880d681SAndroid Build Coastguard Worker                               const TargetLibraryInfo *TLI,
1212*9880d681SAndroid Build Coastguard Worker                               const DominatorTree *DT, AssumptionCache *AC,
1213*9880d681SAndroid Build Coastguard Worker                               const Instruction *CxtI) {
1214*9880d681SAndroid Build Coastguard Worker   return ::SimplifySRemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1215*9880d681SAndroid Build Coastguard Worker                             RecursionLimit);
1216*9880d681SAndroid Build Coastguard Worker }
1217*9880d681SAndroid Build Coastguard Worker 
1218*9880d681SAndroid Build Coastguard Worker /// Given operands for a URem, see if we can fold the result.
1219*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifyURemInst(Value * Op0,Value * Op1,const Query & Q,unsigned MaxRecurse)1220*9880d681SAndroid Build Coastguard Worker static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
1221*9880d681SAndroid Build Coastguard Worker                                unsigned MaxRecurse) {
1222*9880d681SAndroid Build Coastguard Worker   if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
1223*9880d681SAndroid Build Coastguard Worker     return V;
1224*9880d681SAndroid Build Coastguard Worker 
1225*9880d681SAndroid Build Coastguard Worker   return nullptr;
1226*9880d681SAndroid Build Coastguard Worker }
1227*9880d681SAndroid Build Coastguard Worker 
SimplifyURemInst(Value * Op0,Value * Op1,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)1228*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout &DL,
1229*9880d681SAndroid Build Coastguard Worker                               const TargetLibraryInfo *TLI,
1230*9880d681SAndroid Build Coastguard Worker                               const DominatorTree *DT, AssumptionCache *AC,
1231*9880d681SAndroid Build Coastguard Worker                               const Instruction *CxtI) {
1232*9880d681SAndroid Build Coastguard Worker   return ::SimplifyURemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1233*9880d681SAndroid Build Coastguard Worker                             RecursionLimit);
1234*9880d681SAndroid Build Coastguard Worker }
1235*9880d681SAndroid Build Coastguard Worker 
SimplifyFRemInst(Value * Op0,Value * Op1,FastMathFlags FMF,const Query &,unsigned)1236*9880d681SAndroid Build Coastguard Worker static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1237*9880d681SAndroid Build Coastguard Worker                                const Query &, unsigned) {
1238*9880d681SAndroid Build Coastguard Worker   // undef % X -> undef    (the undef could be a snan).
1239*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_Undef()))
1240*9880d681SAndroid Build Coastguard Worker     return Op0;
1241*9880d681SAndroid Build Coastguard Worker 
1242*9880d681SAndroid Build Coastguard Worker   // X % undef -> undef
1243*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Undef()))
1244*9880d681SAndroid Build Coastguard Worker     return Op1;
1245*9880d681SAndroid Build Coastguard Worker 
1246*9880d681SAndroid Build Coastguard Worker   // 0 % X -> 0
1247*9880d681SAndroid Build Coastguard Worker   // Requires that NaNs are off (X could be zero) and signed zeroes are
1248*9880d681SAndroid Build Coastguard Worker   // ignored (X could be positive or negative, so the output sign is unknown).
1249*9880d681SAndroid Build Coastguard Worker   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1250*9880d681SAndroid Build Coastguard Worker     return Op0;
1251*9880d681SAndroid Build Coastguard Worker 
1252*9880d681SAndroid Build Coastguard Worker   return nullptr;
1253*9880d681SAndroid Build Coastguard Worker }
1254*9880d681SAndroid Build Coastguard Worker 
SimplifyFRemInst(Value * Op0,Value * Op1,FastMathFlags FMF,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)1255*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1256*9880d681SAndroid Build Coastguard Worker                               const DataLayout &DL,
1257*9880d681SAndroid Build Coastguard Worker                               const TargetLibraryInfo *TLI,
1258*9880d681SAndroid Build Coastguard Worker                               const DominatorTree *DT, AssumptionCache *AC,
1259*9880d681SAndroid Build Coastguard Worker                               const Instruction *CxtI) {
1260*9880d681SAndroid Build Coastguard Worker   return ::SimplifyFRemInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
1261*9880d681SAndroid Build Coastguard Worker                             RecursionLimit);
1262*9880d681SAndroid Build Coastguard Worker }
1263*9880d681SAndroid Build Coastguard Worker 
1264*9880d681SAndroid Build Coastguard Worker /// Returns true if a shift by \c Amount always yields undef.
isUndefShift(Value * Amount)1265*9880d681SAndroid Build Coastguard Worker static bool isUndefShift(Value *Amount) {
1266*9880d681SAndroid Build Coastguard Worker   Constant *C = dyn_cast<Constant>(Amount);
1267*9880d681SAndroid Build Coastguard Worker   if (!C)
1268*9880d681SAndroid Build Coastguard Worker     return false;
1269*9880d681SAndroid Build Coastguard Worker 
1270*9880d681SAndroid Build Coastguard Worker   // X shift by undef -> undef because it may shift by the bitwidth.
1271*9880d681SAndroid Build Coastguard Worker   if (isa<UndefValue>(C))
1272*9880d681SAndroid Build Coastguard Worker     return true;
1273*9880d681SAndroid Build Coastguard Worker 
1274*9880d681SAndroid Build Coastguard Worker   // Shifting by the bitwidth or more is undefined.
1275*9880d681SAndroid Build Coastguard Worker   if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1276*9880d681SAndroid Build Coastguard Worker     if (CI->getValue().getLimitedValue() >=
1277*9880d681SAndroid Build Coastguard Worker         CI->getType()->getScalarSizeInBits())
1278*9880d681SAndroid Build Coastguard Worker       return true;
1279*9880d681SAndroid Build Coastguard Worker 
1280*9880d681SAndroid Build Coastguard Worker   // If all lanes of a vector shift are undefined the whole shift is.
1281*9880d681SAndroid Build Coastguard Worker   if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1282*9880d681SAndroid Build Coastguard Worker     for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1283*9880d681SAndroid Build Coastguard Worker       if (!isUndefShift(C->getAggregateElement(I)))
1284*9880d681SAndroid Build Coastguard Worker         return false;
1285*9880d681SAndroid Build Coastguard Worker     return true;
1286*9880d681SAndroid Build Coastguard Worker   }
1287*9880d681SAndroid Build Coastguard Worker 
1288*9880d681SAndroid Build Coastguard Worker   return false;
1289*9880d681SAndroid Build Coastguard Worker }
1290*9880d681SAndroid Build Coastguard Worker 
1291*9880d681SAndroid Build Coastguard Worker /// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1292*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifyShift(unsigned Opcode,Value * Op0,Value * Op1,const Query & Q,unsigned MaxRecurse)1293*9880d681SAndroid Build Coastguard Worker static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1294*9880d681SAndroid Build Coastguard Worker                             const Query &Q, unsigned MaxRecurse) {
1295*9880d681SAndroid Build Coastguard Worker   if (Constant *C0 = dyn_cast<Constant>(Op0))
1296*9880d681SAndroid Build Coastguard Worker     if (Constant *C1 = dyn_cast<Constant>(Op1))
1297*9880d681SAndroid Build Coastguard Worker       return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
1298*9880d681SAndroid Build Coastguard Worker 
1299*9880d681SAndroid Build Coastguard Worker   // 0 shift by X -> 0
1300*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_Zero()))
1301*9880d681SAndroid Build Coastguard Worker     return Op0;
1302*9880d681SAndroid Build Coastguard Worker 
1303*9880d681SAndroid Build Coastguard Worker   // X shift by 0 -> X
1304*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Zero()))
1305*9880d681SAndroid Build Coastguard Worker     return Op0;
1306*9880d681SAndroid Build Coastguard Worker 
1307*9880d681SAndroid Build Coastguard Worker   // Fold undefined shifts.
1308*9880d681SAndroid Build Coastguard Worker   if (isUndefShift(Op1))
1309*9880d681SAndroid Build Coastguard Worker     return UndefValue::get(Op0->getType());
1310*9880d681SAndroid Build Coastguard Worker 
1311*9880d681SAndroid Build Coastguard Worker   // If the operation is with the result of a select instruction, check whether
1312*9880d681SAndroid Build Coastguard Worker   // operating on either branch of the select always yields the same value.
1313*9880d681SAndroid Build Coastguard Worker   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1314*9880d681SAndroid Build Coastguard Worker     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1315*9880d681SAndroid Build Coastguard Worker       return V;
1316*9880d681SAndroid Build Coastguard Worker 
1317*9880d681SAndroid Build Coastguard Worker   // If the operation is with the result of a phi instruction, check whether
1318*9880d681SAndroid Build Coastguard Worker   // operating on all incoming values of the phi always yields the same value.
1319*9880d681SAndroid Build Coastguard Worker   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1320*9880d681SAndroid Build Coastguard Worker     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1321*9880d681SAndroid Build Coastguard Worker       return V;
1322*9880d681SAndroid Build Coastguard Worker 
1323*9880d681SAndroid Build Coastguard Worker   // If any bits in the shift amount make that value greater than or equal to
1324*9880d681SAndroid Build Coastguard Worker   // the number of bits in the type, the shift is undefined.
1325*9880d681SAndroid Build Coastguard Worker   unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
1326*9880d681SAndroid Build Coastguard Worker   APInt KnownZero(BitWidth, 0);
1327*9880d681SAndroid Build Coastguard Worker   APInt KnownOne(BitWidth, 0);
1328*9880d681SAndroid Build Coastguard Worker   computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1329*9880d681SAndroid Build Coastguard Worker   if (KnownOne.getLimitedValue() >= BitWidth)
1330*9880d681SAndroid Build Coastguard Worker     return UndefValue::get(Op0->getType());
1331*9880d681SAndroid Build Coastguard Worker 
1332*9880d681SAndroid Build Coastguard Worker   // If all valid bits in the shift amount are known zero, the first operand is
1333*9880d681SAndroid Build Coastguard Worker   // unchanged.
1334*9880d681SAndroid Build Coastguard Worker   unsigned NumValidShiftBits = Log2_32_Ceil(BitWidth);
1335*9880d681SAndroid Build Coastguard Worker   APInt ShiftAmountMask = APInt::getLowBitsSet(BitWidth, NumValidShiftBits);
1336*9880d681SAndroid Build Coastguard Worker   if ((KnownZero & ShiftAmountMask) == ShiftAmountMask)
1337*9880d681SAndroid Build Coastguard Worker     return Op0;
1338*9880d681SAndroid Build Coastguard Worker 
1339*9880d681SAndroid Build Coastguard Worker   return nullptr;
1340*9880d681SAndroid Build Coastguard Worker }
1341*9880d681SAndroid Build Coastguard Worker 
1342*9880d681SAndroid Build Coastguard Worker /// \brief Given operands for an Shl, LShr or AShr, see if we can
1343*9880d681SAndroid Build Coastguard Worker /// fold the result.  If not, this returns null.
SimplifyRightShift(unsigned Opcode,Value * Op0,Value * Op1,bool isExact,const Query & Q,unsigned MaxRecurse)1344*9880d681SAndroid Build Coastguard Worker static Value *SimplifyRightShift(unsigned Opcode, Value *Op0, Value *Op1,
1345*9880d681SAndroid Build Coastguard Worker                                  bool isExact, const Query &Q,
1346*9880d681SAndroid Build Coastguard Worker                                  unsigned MaxRecurse) {
1347*9880d681SAndroid Build Coastguard Worker   if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1348*9880d681SAndroid Build Coastguard Worker     return V;
1349*9880d681SAndroid Build Coastguard Worker 
1350*9880d681SAndroid Build Coastguard Worker   // X >> X -> 0
1351*9880d681SAndroid Build Coastguard Worker   if (Op0 == Op1)
1352*9880d681SAndroid Build Coastguard Worker     return Constant::getNullValue(Op0->getType());
1353*9880d681SAndroid Build Coastguard Worker 
1354*9880d681SAndroid Build Coastguard Worker   // undef >> X -> 0
1355*9880d681SAndroid Build Coastguard Worker   // undef >> X -> undef (if it's exact)
1356*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_Undef()))
1357*9880d681SAndroid Build Coastguard Worker     return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1358*9880d681SAndroid Build Coastguard Worker 
1359*9880d681SAndroid Build Coastguard Worker   // The low bit cannot be shifted out of an exact shift if it is set.
1360*9880d681SAndroid Build Coastguard Worker   if (isExact) {
1361*9880d681SAndroid Build Coastguard Worker     unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
1362*9880d681SAndroid Build Coastguard Worker     APInt Op0KnownZero(BitWidth, 0);
1363*9880d681SAndroid Build Coastguard Worker     APInt Op0KnownOne(BitWidth, 0);
1364*9880d681SAndroid Build Coastguard Worker     computeKnownBits(Op0, Op0KnownZero, Op0KnownOne, Q.DL, /*Depth=*/0, Q.AC,
1365*9880d681SAndroid Build Coastguard Worker                      Q.CxtI, Q.DT);
1366*9880d681SAndroid Build Coastguard Worker     if (Op0KnownOne[0])
1367*9880d681SAndroid Build Coastguard Worker       return Op0;
1368*9880d681SAndroid Build Coastguard Worker   }
1369*9880d681SAndroid Build Coastguard Worker 
1370*9880d681SAndroid Build Coastguard Worker   return nullptr;
1371*9880d681SAndroid Build Coastguard Worker }
1372*9880d681SAndroid Build Coastguard Worker 
1373*9880d681SAndroid Build Coastguard Worker /// Given operands for an Shl, see if we can fold the result.
1374*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifyShlInst(Value * Op0,Value * Op1,bool isNSW,bool isNUW,const Query & Q,unsigned MaxRecurse)1375*9880d681SAndroid Build Coastguard Worker static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1376*9880d681SAndroid Build Coastguard Worker                               const Query &Q, unsigned MaxRecurse) {
1377*9880d681SAndroid Build Coastguard Worker   if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
1378*9880d681SAndroid Build Coastguard Worker     return V;
1379*9880d681SAndroid Build Coastguard Worker 
1380*9880d681SAndroid Build Coastguard Worker   // undef << X -> 0
1381*9880d681SAndroid Build Coastguard Worker   // undef << X -> undef if (if it's NSW/NUW)
1382*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_Undef()))
1383*9880d681SAndroid Build Coastguard Worker     return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
1384*9880d681SAndroid Build Coastguard Worker 
1385*9880d681SAndroid Build Coastguard Worker   // (X >> A) << A -> X
1386*9880d681SAndroid Build Coastguard Worker   Value *X;
1387*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1388*9880d681SAndroid Build Coastguard Worker     return X;
1389*9880d681SAndroid Build Coastguard Worker   return nullptr;
1390*9880d681SAndroid Build Coastguard Worker }
1391*9880d681SAndroid Build Coastguard Worker 
SimplifyShlInst(Value * Op0,Value * Op1,bool isNSW,bool isNUW,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)1392*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1393*9880d681SAndroid Build Coastguard Worker                              const DataLayout &DL, const TargetLibraryInfo *TLI,
1394*9880d681SAndroid Build Coastguard Worker                              const DominatorTree *DT, AssumptionCache *AC,
1395*9880d681SAndroid Build Coastguard Worker                              const Instruction *CxtI) {
1396*9880d681SAndroid Build Coastguard Worker   return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
1397*9880d681SAndroid Build Coastguard Worker                            RecursionLimit);
1398*9880d681SAndroid Build Coastguard Worker }
1399*9880d681SAndroid Build Coastguard Worker 
1400*9880d681SAndroid Build Coastguard Worker /// Given operands for an LShr, see if we can fold the result.
1401*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifyLShrInst(Value * Op0,Value * Op1,bool isExact,const Query & Q,unsigned MaxRecurse)1402*9880d681SAndroid Build Coastguard Worker static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1403*9880d681SAndroid Build Coastguard Worker                                const Query &Q, unsigned MaxRecurse) {
1404*9880d681SAndroid Build Coastguard Worker   if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1405*9880d681SAndroid Build Coastguard Worker                                     MaxRecurse))
1406*9880d681SAndroid Build Coastguard Worker       return V;
1407*9880d681SAndroid Build Coastguard Worker 
1408*9880d681SAndroid Build Coastguard Worker   // (X << A) >> A -> X
1409*9880d681SAndroid Build Coastguard Worker   Value *X;
1410*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
1411*9880d681SAndroid Build Coastguard Worker     return X;
1412*9880d681SAndroid Build Coastguard Worker 
1413*9880d681SAndroid Build Coastguard Worker   return nullptr;
1414*9880d681SAndroid Build Coastguard Worker }
1415*9880d681SAndroid Build Coastguard Worker 
SimplifyLShrInst(Value * Op0,Value * Op1,bool isExact,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)1416*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1417*9880d681SAndroid Build Coastguard Worker                               const DataLayout &DL,
1418*9880d681SAndroid Build Coastguard Worker                               const TargetLibraryInfo *TLI,
1419*9880d681SAndroid Build Coastguard Worker                               const DominatorTree *DT, AssumptionCache *AC,
1420*9880d681SAndroid Build Coastguard Worker                               const Instruction *CxtI) {
1421*9880d681SAndroid Build Coastguard Worker   return ::SimplifyLShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
1422*9880d681SAndroid Build Coastguard Worker                             RecursionLimit);
1423*9880d681SAndroid Build Coastguard Worker }
1424*9880d681SAndroid Build Coastguard Worker 
1425*9880d681SAndroid Build Coastguard Worker /// Given operands for an AShr, see if we can fold the result.
1426*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifyAShrInst(Value * Op0,Value * Op1,bool isExact,const Query & Q,unsigned MaxRecurse)1427*9880d681SAndroid Build Coastguard Worker static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1428*9880d681SAndroid Build Coastguard Worker                                const Query &Q, unsigned MaxRecurse) {
1429*9880d681SAndroid Build Coastguard Worker   if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1430*9880d681SAndroid Build Coastguard Worker                                     MaxRecurse))
1431*9880d681SAndroid Build Coastguard Worker     return V;
1432*9880d681SAndroid Build Coastguard Worker 
1433*9880d681SAndroid Build Coastguard Worker   // all ones >>a X -> all ones
1434*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_AllOnes()))
1435*9880d681SAndroid Build Coastguard Worker     return Op0;
1436*9880d681SAndroid Build Coastguard Worker 
1437*9880d681SAndroid Build Coastguard Worker   // (X << A) >> A -> X
1438*9880d681SAndroid Build Coastguard Worker   Value *X;
1439*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
1440*9880d681SAndroid Build Coastguard Worker     return X;
1441*9880d681SAndroid Build Coastguard Worker 
1442*9880d681SAndroid Build Coastguard Worker   // Arithmetic shifting an all-sign-bit value is a no-op.
1443*9880d681SAndroid Build Coastguard Worker   unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1444*9880d681SAndroid Build Coastguard Worker   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1445*9880d681SAndroid Build Coastguard Worker     return Op0;
1446*9880d681SAndroid Build Coastguard Worker 
1447*9880d681SAndroid Build Coastguard Worker   return nullptr;
1448*9880d681SAndroid Build Coastguard Worker }
1449*9880d681SAndroid Build Coastguard Worker 
SimplifyAShrInst(Value * Op0,Value * Op1,bool isExact,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)1450*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1451*9880d681SAndroid Build Coastguard Worker                               const DataLayout &DL,
1452*9880d681SAndroid Build Coastguard Worker                               const TargetLibraryInfo *TLI,
1453*9880d681SAndroid Build Coastguard Worker                               const DominatorTree *DT, AssumptionCache *AC,
1454*9880d681SAndroid Build Coastguard Worker                               const Instruction *CxtI) {
1455*9880d681SAndroid Build Coastguard Worker   return ::SimplifyAShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
1456*9880d681SAndroid Build Coastguard Worker                             RecursionLimit);
1457*9880d681SAndroid Build Coastguard Worker }
1458*9880d681SAndroid Build Coastguard Worker 
simplifyUnsignedRangeCheck(ICmpInst * ZeroICmp,ICmpInst * UnsignedICmp,bool IsAnd)1459*9880d681SAndroid Build Coastguard Worker static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1460*9880d681SAndroid Build Coastguard Worker                                          ICmpInst *UnsignedICmp, bool IsAnd) {
1461*9880d681SAndroid Build Coastguard Worker   Value *X, *Y;
1462*9880d681SAndroid Build Coastguard Worker 
1463*9880d681SAndroid Build Coastguard Worker   ICmpInst::Predicate EqPred;
1464*9880d681SAndroid Build Coastguard Worker   if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1465*9880d681SAndroid Build Coastguard Worker       !ICmpInst::isEquality(EqPred))
1466*9880d681SAndroid Build Coastguard Worker     return nullptr;
1467*9880d681SAndroid Build Coastguard Worker 
1468*9880d681SAndroid Build Coastguard Worker   ICmpInst::Predicate UnsignedPred;
1469*9880d681SAndroid Build Coastguard Worker   if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1470*9880d681SAndroid Build Coastguard Worker       ICmpInst::isUnsigned(UnsignedPred))
1471*9880d681SAndroid Build Coastguard Worker     ;
1472*9880d681SAndroid Build Coastguard Worker   else if (match(UnsignedICmp,
1473*9880d681SAndroid Build Coastguard Worker                  m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
1474*9880d681SAndroid Build Coastguard Worker            ICmpInst::isUnsigned(UnsignedPred))
1475*9880d681SAndroid Build Coastguard Worker     UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1476*9880d681SAndroid Build Coastguard Worker   else
1477*9880d681SAndroid Build Coastguard Worker     return nullptr;
1478*9880d681SAndroid Build Coastguard Worker 
1479*9880d681SAndroid Build Coastguard Worker   // X < Y && Y != 0  -->  X < Y
1480*9880d681SAndroid Build Coastguard Worker   // X < Y || Y != 0  -->  Y != 0
1481*9880d681SAndroid Build Coastguard Worker   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1482*9880d681SAndroid Build Coastguard Worker     return IsAnd ? UnsignedICmp : ZeroICmp;
1483*9880d681SAndroid Build Coastguard Worker 
1484*9880d681SAndroid Build Coastguard Worker   // X >= Y || Y != 0  -->  true
1485*9880d681SAndroid Build Coastguard Worker   // X >= Y || Y == 0  -->  X >= Y
1486*9880d681SAndroid Build Coastguard Worker   if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1487*9880d681SAndroid Build Coastguard Worker     if (EqPred == ICmpInst::ICMP_NE)
1488*9880d681SAndroid Build Coastguard Worker       return getTrue(UnsignedICmp->getType());
1489*9880d681SAndroid Build Coastguard Worker     return UnsignedICmp;
1490*9880d681SAndroid Build Coastguard Worker   }
1491*9880d681SAndroid Build Coastguard Worker 
1492*9880d681SAndroid Build Coastguard Worker   // X < Y && Y == 0  -->  false
1493*9880d681SAndroid Build Coastguard Worker   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1494*9880d681SAndroid Build Coastguard Worker       IsAnd)
1495*9880d681SAndroid Build Coastguard Worker     return getFalse(UnsignedICmp->getType());
1496*9880d681SAndroid Build Coastguard Worker 
1497*9880d681SAndroid Build Coastguard Worker   return nullptr;
1498*9880d681SAndroid Build Coastguard Worker }
1499*9880d681SAndroid Build Coastguard Worker 
SimplifyAndOfICmps(ICmpInst * Op0,ICmpInst * Op1)1500*9880d681SAndroid Build Coastguard Worker static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1501*9880d681SAndroid Build Coastguard Worker   Type *ITy = Op0->getType();
1502*9880d681SAndroid Build Coastguard Worker   ICmpInst::Predicate Pred0, Pred1;
1503*9880d681SAndroid Build Coastguard Worker   ConstantInt *CI1, *CI2;
1504*9880d681SAndroid Build Coastguard Worker   Value *V;
1505*9880d681SAndroid Build Coastguard Worker 
1506*9880d681SAndroid Build Coastguard Worker   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1507*9880d681SAndroid Build Coastguard Worker     return X;
1508*9880d681SAndroid Build Coastguard Worker 
1509*9880d681SAndroid Build Coastguard Worker   // Look for this pattern: (icmp V, C0) & (icmp V, C1)).
1510*9880d681SAndroid Build Coastguard Worker   const APInt *C0, *C1;
1511*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_ICmp(Pred0, m_Value(V), m_APInt(C0))) &&
1512*9880d681SAndroid Build Coastguard Worker       match(Op1, m_ICmp(Pred1, m_Specific(V), m_APInt(C1)))) {
1513*9880d681SAndroid Build Coastguard Worker     // Make a constant range that's the intersection of the two icmp ranges.
1514*9880d681SAndroid Build Coastguard Worker     // If the intersection is empty, we know that the result is false.
1515*9880d681SAndroid Build Coastguard Worker     auto Range0 = ConstantRange::makeAllowedICmpRegion(Pred0, *C0);
1516*9880d681SAndroid Build Coastguard Worker     auto Range1 = ConstantRange::makeAllowedICmpRegion(Pred1, *C1);
1517*9880d681SAndroid Build Coastguard Worker     if (Range0.intersectWith(Range1).isEmptySet())
1518*9880d681SAndroid Build Coastguard Worker       return getFalse(ITy);
1519*9880d681SAndroid Build Coastguard Worker   }
1520*9880d681SAndroid Build Coastguard Worker 
1521*9880d681SAndroid Build Coastguard Worker   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
1522*9880d681SAndroid Build Coastguard Worker                          m_ConstantInt(CI2))))
1523*9880d681SAndroid Build Coastguard Worker     return nullptr;
1524*9880d681SAndroid Build Coastguard Worker 
1525*9880d681SAndroid Build Coastguard Worker   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
1526*9880d681SAndroid Build Coastguard Worker     return nullptr;
1527*9880d681SAndroid Build Coastguard Worker 
1528*9880d681SAndroid Build Coastguard Worker   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1529*9880d681SAndroid Build Coastguard Worker   bool isNSW = AddInst->hasNoSignedWrap();
1530*9880d681SAndroid Build Coastguard Worker   bool isNUW = AddInst->hasNoUnsignedWrap();
1531*9880d681SAndroid Build Coastguard Worker 
1532*9880d681SAndroid Build Coastguard Worker   const APInt &CI1V = CI1->getValue();
1533*9880d681SAndroid Build Coastguard Worker   const APInt &CI2V = CI2->getValue();
1534*9880d681SAndroid Build Coastguard Worker   const APInt Delta = CI2V - CI1V;
1535*9880d681SAndroid Build Coastguard Worker   if (CI1V.isStrictlyPositive()) {
1536*9880d681SAndroid Build Coastguard Worker     if (Delta == 2) {
1537*9880d681SAndroid Build Coastguard Worker       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1538*9880d681SAndroid Build Coastguard Worker         return getFalse(ITy);
1539*9880d681SAndroid Build Coastguard Worker       if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1540*9880d681SAndroid Build Coastguard Worker         return getFalse(ITy);
1541*9880d681SAndroid Build Coastguard Worker     }
1542*9880d681SAndroid Build Coastguard Worker     if (Delta == 1) {
1543*9880d681SAndroid Build Coastguard Worker       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1544*9880d681SAndroid Build Coastguard Worker         return getFalse(ITy);
1545*9880d681SAndroid Build Coastguard Worker       if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1546*9880d681SAndroid Build Coastguard Worker         return getFalse(ITy);
1547*9880d681SAndroid Build Coastguard Worker     }
1548*9880d681SAndroid Build Coastguard Worker   }
1549*9880d681SAndroid Build Coastguard Worker   if (CI1V.getBoolValue() && isNUW) {
1550*9880d681SAndroid Build Coastguard Worker     if (Delta == 2)
1551*9880d681SAndroid Build Coastguard Worker       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1552*9880d681SAndroid Build Coastguard Worker         return getFalse(ITy);
1553*9880d681SAndroid Build Coastguard Worker     if (Delta == 1)
1554*9880d681SAndroid Build Coastguard Worker       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1555*9880d681SAndroid Build Coastguard Worker         return getFalse(ITy);
1556*9880d681SAndroid Build Coastguard Worker   }
1557*9880d681SAndroid Build Coastguard Worker 
1558*9880d681SAndroid Build Coastguard Worker   return nullptr;
1559*9880d681SAndroid Build Coastguard Worker }
1560*9880d681SAndroid Build Coastguard Worker 
1561*9880d681SAndroid Build Coastguard Worker /// Given operands for an And, see if we can fold the result.
1562*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifyAndInst(Value * Op0,Value * Op1,const Query & Q,unsigned MaxRecurse)1563*9880d681SAndroid Build Coastguard Worker static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
1564*9880d681SAndroid Build Coastguard Worker                               unsigned MaxRecurse) {
1565*9880d681SAndroid Build Coastguard Worker   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1566*9880d681SAndroid Build Coastguard Worker     if (Constant *CRHS = dyn_cast<Constant>(Op1))
1567*9880d681SAndroid Build Coastguard Worker       return ConstantFoldBinaryOpOperands(Instruction::And, CLHS, CRHS, Q.DL);
1568*9880d681SAndroid Build Coastguard Worker 
1569*9880d681SAndroid Build Coastguard Worker     // Canonicalize the constant to the RHS.
1570*9880d681SAndroid Build Coastguard Worker     std::swap(Op0, Op1);
1571*9880d681SAndroid Build Coastguard Worker   }
1572*9880d681SAndroid Build Coastguard Worker 
1573*9880d681SAndroid Build Coastguard Worker   // X & undef -> 0
1574*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Undef()))
1575*9880d681SAndroid Build Coastguard Worker     return Constant::getNullValue(Op0->getType());
1576*9880d681SAndroid Build Coastguard Worker 
1577*9880d681SAndroid Build Coastguard Worker   // X & X = X
1578*9880d681SAndroid Build Coastguard Worker   if (Op0 == Op1)
1579*9880d681SAndroid Build Coastguard Worker     return Op0;
1580*9880d681SAndroid Build Coastguard Worker 
1581*9880d681SAndroid Build Coastguard Worker   // X & 0 = 0
1582*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Zero()))
1583*9880d681SAndroid Build Coastguard Worker     return Op1;
1584*9880d681SAndroid Build Coastguard Worker 
1585*9880d681SAndroid Build Coastguard Worker   // X & -1 = X
1586*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_AllOnes()))
1587*9880d681SAndroid Build Coastguard Worker     return Op0;
1588*9880d681SAndroid Build Coastguard Worker 
1589*9880d681SAndroid Build Coastguard Worker   // A & ~A  =  ~A & A  =  0
1590*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_Not(m_Specific(Op1))) ||
1591*9880d681SAndroid Build Coastguard Worker       match(Op1, m_Not(m_Specific(Op0))))
1592*9880d681SAndroid Build Coastguard Worker     return Constant::getNullValue(Op0->getType());
1593*9880d681SAndroid Build Coastguard Worker 
1594*9880d681SAndroid Build Coastguard Worker   // (A | ?) & A = A
1595*9880d681SAndroid Build Coastguard Worker   Value *A = nullptr, *B = nullptr;
1596*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1597*9880d681SAndroid Build Coastguard Worker       (A == Op1 || B == Op1))
1598*9880d681SAndroid Build Coastguard Worker     return Op1;
1599*9880d681SAndroid Build Coastguard Worker 
1600*9880d681SAndroid Build Coastguard Worker   // A & (A | ?) = A
1601*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1602*9880d681SAndroid Build Coastguard Worker       (A == Op0 || B == Op0))
1603*9880d681SAndroid Build Coastguard Worker     return Op0;
1604*9880d681SAndroid Build Coastguard Worker 
1605*9880d681SAndroid Build Coastguard Worker   // A & (-A) = A if A is a power of two or zero.
1606*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_Neg(m_Specific(Op1))) ||
1607*9880d681SAndroid Build Coastguard Worker       match(Op1, m_Neg(m_Specific(Op0)))) {
1608*9880d681SAndroid Build Coastguard Worker     if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1609*9880d681SAndroid Build Coastguard Worker                                Q.DT))
1610*9880d681SAndroid Build Coastguard Worker       return Op0;
1611*9880d681SAndroid Build Coastguard Worker     if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1612*9880d681SAndroid Build Coastguard Worker                                Q.DT))
1613*9880d681SAndroid Build Coastguard Worker       return Op1;
1614*9880d681SAndroid Build Coastguard Worker   }
1615*9880d681SAndroid Build Coastguard Worker 
1616*9880d681SAndroid Build Coastguard Worker   if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1617*9880d681SAndroid Build Coastguard Worker     if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1618*9880d681SAndroid Build Coastguard Worker       if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
1619*9880d681SAndroid Build Coastguard Worker         return V;
1620*9880d681SAndroid Build Coastguard Worker       if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
1621*9880d681SAndroid Build Coastguard Worker         return V;
1622*9880d681SAndroid Build Coastguard Worker     }
1623*9880d681SAndroid Build Coastguard Worker   }
1624*9880d681SAndroid Build Coastguard Worker 
1625*9880d681SAndroid Build Coastguard Worker   // The compares may be hidden behind casts. Look through those and try the
1626*9880d681SAndroid Build Coastguard Worker   // same folds as above.
1627*9880d681SAndroid Build Coastguard Worker   auto *Cast0 = dyn_cast<CastInst>(Op0);
1628*9880d681SAndroid Build Coastguard Worker   auto *Cast1 = dyn_cast<CastInst>(Op1);
1629*9880d681SAndroid Build Coastguard Worker   if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1630*9880d681SAndroid Build Coastguard Worker       Cast0->getSrcTy() == Cast1->getSrcTy()) {
1631*9880d681SAndroid Build Coastguard Worker     auto *Cmp0 = dyn_cast<ICmpInst>(Cast0->getOperand(0));
1632*9880d681SAndroid Build Coastguard Worker     auto *Cmp1 = dyn_cast<ICmpInst>(Cast1->getOperand(0));
1633*9880d681SAndroid Build Coastguard Worker     if (Cmp0 && Cmp1) {
1634*9880d681SAndroid Build Coastguard Worker       Instruction::CastOps CastOpc = Cast0->getOpcode();
1635*9880d681SAndroid Build Coastguard Worker       Type *ResultType = Cast0->getType();
1636*9880d681SAndroid Build Coastguard Worker       if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp0, Cmp1)))
1637*9880d681SAndroid Build Coastguard Worker         return ConstantExpr::getCast(CastOpc, V, ResultType);
1638*9880d681SAndroid Build Coastguard Worker       if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp1, Cmp0)))
1639*9880d681SAndroid Build Coastguard Worker         return ConstantExpr::getCast(CastOpc, V, ResultType);
1640*9880d681SAndroid Build Coastguard Worker     }
1641*9880d681SAndroid Build Coastguard Worker   }
1642*9880d681SAndroid Build Coastguard Worker 
1643*9880d681SAndroid Build Coastguard Worker   // Try some generic simplifications for associative operations.
1644*9880d681SAndroid Build Coastguard Worker   if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1645*9880d681SAndroid Build Coastguard Worker                                           MaxRecurse))
1646*9880d681SAndroid Build Coastguard Worker     return V;
1647*9880d681SAndroid Build Coastguard Worker 
1648*9880d681SAndroid Build Coastguard Worker   // And distributes over Or.  Try some generic simplifications based on this.
1649*9880d681SAndroid Build Coastguard Worker   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1650*9880d681SAndroid Build Coastguard Worker                              Q, MaxRecurse))
1651*9880d681SAndroid Build Coastguard Worker     return V;
1652*9880d681SAndroid Build Coastguard Worker 
1653*9880d681SAndroid Build Coastguard Worker   // And distributes over Xor.  Try some generic simplifications based on this.
1654*9880d681SAndroid Build Coastguard Worker   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1655*9880d681SAndroid Build Coastguard Worker                              Q, MaxRecurse))
1656*9880d681SAndroid Build Coastguard Worker     return V;
1657*9880d681SAndroid Build Coastguard Worker 
1658*9880d681SAndroid Build Coastguard Worker   // If the operation is with the result of a select instruction, check whether
1659*9880d681SAndroid Build Coastguard Worker   // operating on either branch of the select always yields the same value.
1660*9880d681SAndroid Build Coastguard Worker   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1661*9880d681SAndroid Build Coastguard Worker     if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1662*9880d681SAndroid Build Coastguard Worker                                          MaxRecurse))
1663*9880d681SAndroid Build Coastguard Worker       return V;
1664*9880d681SAndroid Build Coastguard Worker 
1665*9880d681SAndroid Build Coastguard Worker   // If the operation is with the result of a phi instruction, check whether
1666*9880d681SAndroid Build Coastguard Worker   // operating on all incoming values of the phi always yields the same value.
1667*9880d681SAndroid Build Coastguard Worker   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1668*9880d681SAndroid Build Coastguard Worker     if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
1669*9880d681SAndroid Build Coastguard Worker                                       MaxRecurse))
1670*9880d681SAndroid Build Coastguard Worker       return V;
1671*9880d681SAndroid Build Coastguard Worker 
1672*9880d681SAndroid Build Coastguard Worker   return nullptr;
1673*9880d681SAndroid Build Coastguard Worker }
1674*9880d681SAndroid Build Coastguard Worker 
SimplifyAndInst(Value * Op0,Value * Op1,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)1675*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout &DL,
1676*9880d681SAndroid Build Coastguard Worker                              const TargetLibraryInfo *TLI,
1677*9880d681SAndroid Build Coastguard Worker                              const DominatorTree *DT, AssumptionCache *AC,
1678*9880d681SAndroid Build Coastguard Worker                              const Instruction *CxtI) {
1679*9880d681SAndroid Build Coastguard Worker   return ::SimplifyAndInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1680*9880d681SAndroid Build Coastguard Worker                            RecursionLimit);
1681*9880d681SAndroid Build Coastguard Worker }
1682*9880d681SAndroid Build Coastguard Worker 
1683*9880d681SAndroid Build Coastguard Worker /// Simplify (or (icmp ...) (icmp ...)) to true when we can tell that the union
1684*9880d681SAndroid Build Coastguard Worker /// contains all possible values.
SimplifyOrOfICmps(ICmpInst * Op0,ICmpInst * Op1)1685*9880d681SAndroid Build Coastguard Worker static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1686*9880d681SAndroid Build Coastguard Worker   ICmpInst::Predicate Pred0, Pred1;
1687*9880d681SAndroid Build Coastguard Worker   ConstantInt *CI1, *CI2;
1688*9880d681SAndroid Build Coastguard Worker   Value *V;
1689*9880d681SAndroid Build Coastguard Worker 
1690*9880d681SAndroid Build Coastguard Worker   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1691*9880d681SAndroid Build Coastguard Worker     return X;
1692*9880d681SAndroid Build Coastguard Worker 
1693*9880d681SAndroid Build Coastguard Worker   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
1694*9880d681SAndroid Build Coastguard Worker                          m_ConstantInt(CI2))))
1695*9880d681SAndroid Build Coastguard Worker    return nullptr;
1696*9880d681SAndroid Build Coastguard Worker 
1697*9880d681SAndroid Build Coastguard Worker   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
1698*9880d681SAndroid Build Coastguard Worker     return nullptr;
1699*9880d681SAndroid Build Coastguard Worker 
1700*9880d681SAndroid Build Coastguard Worker   Type *ITy = Op0->getType();
1701*9880d681SAndroid Build Coastguard Worker 
1702*9880d681SAndroid Build Coastguard Worker   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1703*9880d681SAndroid Build Coastguard Worker   bool isNSW = AddInst->hasNoSignedWrap();
1704*9880d681SAndroid Build Coastguard Worker   bool isNUW = AddInst->hasNoUnsignedWrap();
1705*9880d681SAndroid Build Coastguard Worker 
1706*9880d681SAndroid Build Coastguard Worker   const APInt &CI1V = CI1->getValue();
1707*9880d681SAndroid Build Coastguard Worker   const APInt &CI2V = CI2->getValue();
1708*9880d681SAndroid Build Coastguard Worker   const APInt Delta = CI2V - CI1V;
1709*9880d681SAndroid Build Coastguard Worker   if (CI1V.isStrictlyPositive()) {
1710*9880d681SAndroid Build Coastguard Worker     if (Delta == 2) {
1711*9880d681SAndroid Build Coastguard Worker       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1712*9880d681SAndroid Build Coastguard Worker         return getTrue(ITy);
1713*9880d681SAndroid Build Coastguard Worker       if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1714*9880d681SAndroid Build Coastguard Worker         return getTrue(ITy);
1715*9880d681SAndroid Build Coastguard Worker     }
1716*9880d681SAndroid Build Coastguard Worker     if (Delta == 1) {
1717*9880d681SAndroid Build Coastguard Worker       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1718*9880d681SAndroid Build Coastguard Worker         return getTrue(ITy);
1719*9880d681SAndroid Build Coastguard Worker       if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1720*9880d681SAndroid Build Coastguard Worker         return getTrue(ITy);
1721*9880d681SAndroid Build Coastguard Worker     }
1722*9880d681SAndroid Build Coastguard Worker   }
1723*9880d681SAndroid Build Coastguard Worker   if (CI1V.getBoolValue() && isNUW) {
1724*9880d681SAndroid Build Coastguard Worker     if (Delta == 2)
1725*9880d681SAndroid Build Coastguard Worker       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1726*9880d681SAndroid Build Coastguard Worker         return getTrue(ITy);
1727*9880d681SAndroid Build Coastguard Worker     if (Delta == 1)
1728*9880d681SAndroid Build Coastguard Worker       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1729*9880d681SAndroid Build Coastguard Worker         return getTrue(ITy);
1730*9880d681SAndroid Build Coastguard Worker   }
1731*9880d681SAndroid Build Coastguard Worker 
1732*9880d681SAndroid Build Coastguard Worker   return nullptr;
1733*9880d681SAndroid Build Coastguard Worker }
1734*9880d681SAndroid Build Coastguard Worker 
1735*9880d681SAndroid Build Coastguard Worker /// Given operands for an Or, see if we can fold the result.
1736*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifyOrInst(Value * Op0,Value * Op1,const Query & Q,unsigned MaxRecurse)1737*9880d681SAndroid Build Coastguard Worker static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1738*9880d681SAndroid Build Coastguard Worker                              unsigned MaxRecurse) {
1739*9880d681SAndroid Build Coastguard Worker   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1740*9880d681SAndroid Build Coastguard Worker     if (Constant *CRHS = dyn_cast<Constant>(Op1))
1741*9880d681SAndroid Build Coastguard Worker       return ConstantFoldBinaryOpOperands(Instruction::Or, CLHS, CRHS, Q.DL);
1742*9880d681SAndroid Build Coastguard Worker 
1743*9880d681SAndroid Build Coastguard Worker     // Canonicalize the constant to the RHS.
1744*9880d681SAndroid Build Coastguard Worker     std::swap(Op0, Op1);
1745*9880d681SAndroid Build Coastguard Worker   }
1746*9880d681SAndroid Build Coastguard Worker 
1747*9880d681SAndroid Build Coastguard Worker   // X | undef -> -1
1748*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Undef()))
1749*9880d681SAndroid Build Coastguard Worker     return Constant::getAllOnesValue(Op0->getType());
1750*9880d681SAndroid Build Coastguard Worker 
1751*9880d681SAndroid Build Coastguard Worker   // X | X = X
1752*9880d681SAndroid Build Coastguard Worker   if (Op0 == Op1)
1753*9880d681SAndroid Build Coastguard Worker     return Op0;
1754*9880d681SAndroid Build Coastguard Worker 
1755*9880d681SAndroid Build Coastguard Worker   // X | 0 = X
1756*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Zero()))
1757*9880d681SAndroid Build Coastguard Worker     return Op0;
1758*9880d681SAndroid Build Coastguard Worker 
1759*9880d681SAndroid Build Coastguard Worker   // X | -1 = -1
1760*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_AllOnes()))
1761*9880d681SAndroid Build Coastguard Worker     return Op1;
1762*9880d681SAndroid Build Coastguard Worker 
1763*9880d681SAndroid Build Coastguard Worker   // A | ~A  =  ~A | A  =  -1
1764*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_Not(m_Specific(Op1))) ||
1765*9880d681SAndroid Build Coastguard Worker       match(Op1, m_Not(m_Specific(Op0))))
1766*9880d681SAndroid Build Coastguard Worker     return Constant::getAllOnesValue(Op0->getType());
1767*9880d681SAndroid Build Coastguard Worker 
1768*9880d681SAndroid Build Coastguard Worker   // (A & ?) | A = A
1769*9880d681SAndroid Build Coastguard Worker   Value *A = nullptr, *B = nullptr;
1770*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1771*9880d681SAndroid Build Coastguard Worker       (A == Op1 || B == Op1))
1772*9880d681SAndroid Build Coastguard Worker     return Op1;
1773*9880d681SAndroid Build Coastguard Worker 
1774*9880d681SAndroid Build Coastguard Worker   // A | (A & ?) = A
1775*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1776*9880d681SAndroid Build Coastguard Worker       (A == Op0 || B == Op0))
1777*9880d681SAndroid Build Coastguard Worker     return Op0;
1778*9880d681SAndroid Build Coastguard Worker 
1779*9880d681SAndroid Build Coastguard Worker   // ~(A & ?) | A = -1
1780*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1781*9880d681SAndroid Build Coastguard Worker       (A == Op1 || B == Op1))
1782*9880d681SAndroid Build Coastguard Worker     return Constant::getAllOnesValue(Op1->getType());
1783*9880d681SAndroid Build Coastguard Worker 
1784*9880d681SAndroid Build Coastguard Worker   // A | ~(A & ?) = -1
1785*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1786*9880d681SAndroid Build Coastguard Worker       (A == Op0 || B == Op0))
1787*9880d681SAndroid Build Coastguard Worker     return Constant::getAllOnesValue(Op0->getType());
1788*9880d681SAndroid Build Coastguard Worker 
1789*9880d681SAndroid Build Coastguard Worker   if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1790*9880d681SAndroid Build Coastguard Worker     if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1791*9880d681SAndroid Build Coastguard Worker       if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1792*9880d681SAndroid Build Coastguard Worker         return V;
1793*9880d681SAndroid Build Coastguard Worker       if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1794*9880d681SAndroid Build Coastguard Worker         return V;
1795*9880d681SAndroid Build Coastguard Worker     }
1796*9880d681SAndroid Build Coastguard Worker   }
1797*9880d681SAndroid Build Coastguard Worker 
1798*9880d681SAndroid Build Coastguard Worker   // Try some generic simplifications for associative operations.
1799*9880d681SAndroid Build Coastguard Worker   if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1800*9880d681SAndroid Build Coastguard Worker                                           MaxRecurse))
1801*9880d681SAndroid Build Coastguard Worker     return V;
1802*9880d681SAndroid Build Coastguard Worker 
1803*9880d681SAndroid Build Coastguard Worker   // Or distributes over And.  Try some generic simplifications based on this.
1804*9880d681SAndroid Build Coastguard Worker   if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1805*9880d681SAndroid Build Coastguard Worker                              MaxRecurse))
1806*9880d681SAndroid Build Coastguard Worker     return V;
1807*9880d681SAndroid Build Coastguard Worker 
1808*9880d681SAndroid Build Coastguard Worker   // If the operation is with the result of a select instruction, check whether
1809*9880d681SAndroid Build Coastguard Worker   // operating on either branch of the select always yields the same value.
1810*9880d681SAndroid Build Coastguard Worker   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1811*9880d681SAndroid Build Coastguard Worker     if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
1812*9880d681SAndroid Build Coastguard Worker                                          MaxRecurse))
1813*9880d681SAndroid Build Coastguard Worker       return V;
1814*9880d681SAndroid Build Coastguard Worker 
1815*9880d681SAndroid Build Coastguard Worker   // (A & C)|(B & D)
1816*9880d681SAndroid Build Coastguard Worker   Value *C = nullptr, *D = nullptr;
1817*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1818*9880d681SAndroid Build Coastguard Worker       match(Op1, m_And(m_Value(B), m_Value(D)))) {
1819*9880d681SAndroid Build Coastguard Worker     ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1820*9880d681SAndroid Build Coastguard Worker     ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1821*9880d681SAndroid Build Coastguard Worker     if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1822*9880d681SAndroid Build Coastguard Worker       // (A & C1)|(B & C2)
1823*9880d681SAndroid Build Coastguard Worker       // If we have: ((V + N) & C1) | (V & C2)
1824*9880d681SAndroid Build Coastguard Worker       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1825*9880d681SAndroid Build Coastguard Worker       // replace with V+N.
1826*9880d681SAndroid Build Coastguard Worker       Value *V1, *V2;
1827*9880d681SAndroid Build Coastguard Worker       if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1828*9880d681SAndroid Build Coastguard Worker           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1829*9880d681SAndroid Build Coastguard Worker         // Add commutes, try both ways.
1830*9880d681SAndroid Build Coastguard Worker         if (V1 == B &&
1831*9880d681SAndroid Build Coastguard Worker             MaskedValueIsZero(V2, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1832*9880d681SAndroid Build Coastguard Worker           return A;
1833*9880d681SAndroid Build Coastguard Worker         if (V2 == B &&
1834*9880d681SAndroid Build Coastguard Worker             MaskedValueIsZero(V1, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1835*9880d681SAndroid Build Coastguard Worker           return A;
1836*9880d681SAndroid Build Coastguard Worker       }
1837*9880d681SAndroid Build Coastguard Worker       // Or commutes, try both ways.
1838*9880d681SAndroid Build Coastguard Worker       if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1839*9880d681SAndroid Build Coastguard Worker           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1840*9880d681SAndroid Build Coastguard Worker         // Add commutes, try both ways.
1841*9880d681SAndroid Build Coastguard Worker         if (V1 == A &&
1842*9880d681SAndroid Build Coastguard Worker             MaskedValueIsZero(V2, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1843*9880d681SAndroid Build Coastguard Worker           return B;
1844*9880d681SAndroid Build Coastguard Worker         if (V2 == A &&
1845*9880d681SAndroid Build Coastguard Worker             MaskedValueIsZero(V1, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1846*9880d681SAndroid Build Coastguard Worker           return B;
1847*9880d681SAndroid Build Coastguard Worker       }
1848*9880d681SAndroid Build Coastguard Worker     }
1849*9880d681SAndroid Build Coastguard Worker   }
1850*9880d681SAndroid Build Coastguard Worker 
1851*9880d681SAndroid Build Coastguard Worker   // If the operation is with the result of a phi instruction, check whether
1852*9880d681SAndroid Build Coastguard Worker   // operating on all incoming values of the phi always yields the same value.
1853*9880d681SAndroid Build Coastguard Worker   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1854*9880d681SAndroid Build Coastguard Worker     if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
1855*9880d681SAndroid Build Coastguard Worker       return V;
1856*9880d681SAndroid Build Coastguard Worker 
1857*9880d681SAndroid Build Coastguard Worker   return nullptr;
1858*9880d681SAndroid Build Coastguard Worker }
1859*9880d681SAndroid Build Coastguard Worker 
SimplifyOrInst(Value * Op0,Value * Op1,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)1860*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout &DL,
1861*9880d681SAndroid Build Coastguard Worker                             const TargetLibraryInfo *TLI,
1862*9880d681SAndroid Build Coastguard Worker                             const DominatorTree *DT, AssumptionCache *AC,
1863*9880d681SAndroid Build Coastguard Worker                             const Instruction *CxtI) {
1864*9880d681SAndroid Build Coastguard Worker   return ::SimplifyOrInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1865*9880d681SAndroid Build Coastguard Worker                           RecursionLimit);
1866*9880d681SAndroid Build Coastguard Worker }
1867*9880d681SAndroid Build Coastguard Worker 
1868*9880d681SAndroid Build Coastguard Worker /// Given operands for a Xor, see if we can fold the result.
1869*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifyXorInst(Value * Op0,Value * Op1,const Query & Q,unsigned MaxRecurse)1870*9880d681SAndroid Build Coastguard Worker static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1871*9880d681SAndroid Build Coastguard Worker                               unsigned MaxRecurse) {
1872*9880d681SAndroid Build Coastguard Worker   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1873*9880d681SAndroid Build Coastguard Worker     if (Constant *CRHS = dyn_cast<Constant>(Op1))
1874*9880d681SAndroid Build Coastguard Worker       return ConstantFoldBinaryOpOperands(Instruction::Xor, CLHS, CRHS, Q.DL);
1875*9880d681SAndroid Build Coastguard Worker 
1876*9880d681SAndroid Build Coastguard Worker     // Canonicalize the constant to the RHS.
1877*9880d681SAndroid Build Coastguard Worker     std::swap(Op0, Op1);
1878*9880d681SAndroid Build Coastguard Worker   }
1879*9880d681SAndroid Build Coastguard Worker 
1880*9880d681SAndroid Build Coastguard Worker   // A ^ undef -> undef
1881*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Undef()))
1882*9880d681SAndroid Build Coastguard Worker     return Op1;
1883*9880d681SAndroid Build Coastguard Worker 
1884*9880d681SAndroid Build Coastguard Worker   // A ^ 0 = A
1885*9880d681SAndroid Build Coastguard Worker   if (match(Op1, m_Zero()))
1886*9880d681SAndroid Build Coastguard Worker     return Op0;
1887*9880d681SAndroid Build Coastguard Worker 
1888*9880d681SAndroid Build Coastguard Worker   // A ^ A = 0
1889*9880d681SAndroid Build Coastguard Worker   if (Op0 == Op1)
1890*9880d681SAndroid Build Coastguard Worker     return Constant::getNullValue(Op0->getType());
1891*9880d681SAndroid Build Coastguard Worker 
1892*9880d681SAndroid Build Coastguard Worker   // A ^ ~A  =  ~A ^ A  =  -1
1893*9880d681SAndroid Build Coastguard Worker   if (match(Op0, m_Not(m_Specific(Op1))) ||
1894*9880d681SAndroid Build Coastguard Worker       match(Op1, m_Not(m_Specific(Op0))))
1895*9880d681SAndroid Build Coastguard Worker     return Constant::getAllOnesValue(Op0->getType());
1896*9880d681SAndroid Build Coastguard Worker 
1897*9880d681SAndroid Build Coastguard Worker   // Try some generic simplifications for associative operations.
1898*9880d681SAndroid Build Coastguard Worker   if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1899*9880d681SAndroid Build Coastguard Worker                                           MaxRecurse))
1900*9880d681SAndroid Build Coastguard Worker     return V;
1901*9880d681SAndroid Build Coastguard Worker 
1902*9880d681SAndroid Build Coastguard Worker   // Threading Xor over selects and phi nodes is pointless, so don't bother.
1903*9880d681SAndroid Build Coastguard Worker   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1904*9880d681SAndroid Build Coastguard Worker   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1905*9880d681SAndroid Build Coastguard Worker   // only if B and C are equal.  If B and C are equal then (since we assume
1906*9880d681SAndroid Build Coastguard Worker   // that operands have already been simplified) "select(cond, B, C)" should
1907*9880d681SAndroid Build Coastguard Worker   // have been simplified to the common value of B and C already.  Analysing
1908*9880d681SAndroid Build Coastguard Worker   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
1909*9880d681SAndroid Build Coastguard Worker   // for threading over phi nodes.
1910*9880d681SAndroid Build Coastguard Worker 
1911*9880d681SAndroid Build Coastguard Worker   return nullptr;
1912*9880d681SAndroid Build Coastguard Worker }
1913*9880d681SAndroid Build Coastguard Worker 
SimplifyXorInst(Value * Op0,Value * Op1,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)1914*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout &DL,
1915*9880d681SAndroid Build Coastguard Worker                              const TargetLibraryInfo *TLI,
1916*9880d681SAndroid Build Coastguard Worker                              const DominatorTree *DT, AssumptionCache *AC,
1917*9880d681SAndroid Build Coastguard Worker                              const Instruction *CxtI) {
1918*9880d681SAndroid Build Coastguard Worker   return ::SimplifyXorInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1919*9880d681SAndroid Build Coastguard Worker                            RecursionLimit);
1920*9880d681SAndroid Build Coastguard Worker }
1921*9880d681SAndroid Build Coastguard Worker 
GetCompareTy(Value * Op)1922*9880d681SAndroid Build Coastguard Worker static Type *GetCompareTy(Value *Op) {
1923*9880d681SAndroid Build Coastguard Worker   return CmpInst::makeCmpResultType(Op->getType());
1924*9880d681SAndroid Build Coastguard Worker }
1925*9880d681SAndroid Build Coastguard Worker 
1926*9880d681SAndroid Build Coastguard Worker /// Rummage around inside V looking for something equivalent to the comparison
1927*9880d681SAndroid Build Coastguard Worker /// "LHS Pred RHS". Return such a value if found, otherwise return null.
1928*9880d681SAndroid Build Coastguard Worker /// Helper function for analyzing max/min idioms.
ExtractEquivalentCondition(Value * V,CmpInst::Predicate Pred,Value * LHS,Value * RHS)1929*9880d681SAndroid Build Coastguard Worker static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1930*9880d681SAndroid Build Coastguard Worker                                          Value *LHS, Value *RHS) {
1931*9880d681SAndroid Build Coastguard Worker   SelectInst *SI = dyn_cast<SelectInst>(V);
1932*9880d681SAndroid Build Coastguard Worker   if (!SI)
1933*9880d681SAndroid Build Coastguard Worker     return nullptr;
1934*9880d681SAndroid Build Coastguard Worker   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1935*9880d681SAndroid Build Coastguard Worker   if (!Cmp)
1936*9880d681SAndroid Build Coastguard Worker     return nullptr;
1937*9880d681SAndroid Build Coastguard Worker   Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1938*9880d681SAndroid Build Coastguard Worker   if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1939*9880d681SAndroid Build Coastguard Worker     return Cmp;
1940*9880d681SAndroid Build Coastguard Worker   if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1941*9880d681SAndroid Build Coastguard Worker       LHS == CmpRHS && RHS == CmpLHS)
1942*9880d681SAndroid Build Coastguard Worker     return Cmp;
1943*9880d681SAndroid Build Coastguard Worker   return nullptr;
1944*9880d681SAndroid Build Coastguard Worker }
1945*9880d681SAndroid Build Coastguard Worker 
1946*9880d681SAndroid Build Coastguard Worker // A significant optimization not implemented here is assuming that alloca
1947*9880d681SAndroid Build Coastguard Worker // addresses are not equal to incoming argument values. They don't *alias*,
1948*9880d681SAndroid Build Coastguard Worker // as we say, but that doesn't mean they aren't equal, so we take a
1949*9880d681SAndroid Build Coastguard Worker // conservative approach.
1950*9880d681SAndroid Build Coastguard Worker //
1951*9880d681SAndroid Build Coastguard Worker // This is inspired in part by C++11 5.10p1:
1952*9880d681SAndroid Build Coastguard Worker //   "Two pointers of the same type compare equal if and only if they are both
1953*9880d681SAndroid Build Coastguard Worker //    null, both point to the same function, or both represent the same
1954*9880d681SAndroid Build Coastguard Worker //    address."
1955*9880d681SAndroid Build Coastguard Worker //
1956*9880d681SAndroid Build Coastguard Worker // This is pretty permissive.
1957*9880d681SAndroid Build Coastguard Worker //
1958*9880d681SAndroid Build Coastguard Worker // It's also partly due to C11 6.5.9p6:
1959*9880d681SAndroid Build Coastguard Worker //   "Two pointers compare equal if and only if both are null pointers, both are
1960*9880d681SAndroid Build Coastguard Worker //    pointers to the same object (including a pointer to an object and a
1961*9880d681SAndroid Build Coastguard Worker //    subobject at its beginning) or function, both are pointers to one past the
1962*9880d681SAndroid Build Coastguard Worker //    last element of the same array object, or one is a pointer to one past the
1963*9880d681SAndroid Build Coastguard Worker //    end of one array object and the other is a pointer to the start of a
1964*9880d681SAndroid Build Coastguard Worker //    different array object that happens to immediately follow the first array
1965*9880d681SAndroid Build Coastguard Worker //    object in the address space.)
1966*9880d681SAndroid Build Coastguard Worker //
1967*9880d681SAndroid Build Coastguard Worker // C11's version is more restrictive, however there's no reason why an argument
1968*9880d681SAndroid Build Coastguard Worker // couldn't be a one-past-the-end value for a stack object in the caller and be
1969*9880d681SAndroid Build Coastguard Worker // equal to the beginning of a stack object in the callee.
1970*9880d681SAndroid Build Coastguard Worker //
1971*9880d681SAndroid Build Coastguard Worker // If the C and C++ standards are ever made sufficiently restrictive in this
1972*9880d681SAndroid Build Coastguard Worker // area, it may be possible to update LLVM's semantics accordingly and reinstate
1973*9880d681SAndroid Build Coastguard Worker // this optimization.
1974*9880d681SAndroid Build Coastguard Worker static Constant *
computePointerICmp(const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,CmpInst::Predicate Pred,const Instruction * CxtI,Value * LHS,Value * RHS)1975*9880d681SAndroid Build Coastguard Worker computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
1976*9880d681SAndroid Build Coastguard Worker                    const DominatorTree *DT, CmpInst::Predicate Pred,
1977*9880d681SAndroid Build Coastguard Worker                    const Instruction *CxtI, Value *LHS, Value *RHS) {
1978*9880d681SAndroid Build Coastguard Worker   // First, skip past any trivial no-ops.
1979*9880d681SAndroid Build Coastguard Worker   LHS = LHS->stripPointerCasts();
1980*9880d681SAndroid Build Coastguard Worker   RHS = RHS->stripPointerCasts();
1981*9880d681SAndroid Build Coastguard Worker 
1982*9880d681SAndroid Build Coastguard Worker   // A non-null pointer is not equal to a null pointer.
1983*9880d681SAndroid Build Coastguard Worker   if (llvm::isKnownNonNull(LHS) && isa<ConstantPointerNull>(RHS) &&
1984*9880d681SAndroid Build Coastguard Worker       (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
1985*9880d681SAndroid Build Coastguard Worker     return ConstantInt::get(GetCompareTy(LHS),
1986*9880d681SAndroid Build Coastguard Worker                             !CmpInst::isTrueWhenEqual(Pred));
1987*9880d681SAndroid Build Coastguard Worker 
1988*9880d681SAndroid Build Coastguard Worker   // We can only fold certain predicates on pointer comparisons.
1989*9880d681SAndroid Build Coastguard Worker   switch (Pred) {
1990*9880d681SAndroid Build Coastguard Worker   default:
1991*9880d681SAndroid Build Coastguard Worker     return nullptr;
1992*9880d681SAndroid Build Coastguard Worker 
1993*9880d681SAndroid Build Coastguard Worker     // Equality comaprisons are easy to fold.
1994*9880d681SAndroid Build Coastguard Worker   case CmpInst::ICMP_EQ:
1995*9880d681SAndroid Build Coastguard Worker   case CmpInst::ICMP_NE:
1996*9880d681SAndroid Build Coastguard Worker     break;
1997*9880d681SAndroid Build Coastguard Worker 
1998*9880d681SAndroid Build Coastguard Worker     // We can only handle unsigned relational comparisons because 'inbounds' on
1999*9880d681SAndroid Build Coastguard Worker     // a GEP only protects against unsigned wrapping.
2000*9880d681SAndroid Build Coastguard Worker   case CmpInst::ICMP_UGT:
2001*9880d681SAndroid Build Coastguard Worker   case CmpInst::ICMP_UGE:
2002*9880d681SAndroid Build Coastguard Worker   case CmpInst::ICMP_ULT:
2003*9880d681SAndroid Build Coastguard Worker   case CmpInst::ICMP_ULE:
2004*9880d681SAndroid Build Coastguard Worker     // However, we have to switch them to their signed variants to handle
2005*9880d681SAndroid Build Coastguard Worker     // negative indices from the base pointer.
2006*9880d681SAndroid Build Coastguard Worker     Pred = ICmpInst::getSignedPredicate(Pred);
2007*9880d681SAndroid Build Coastguard Worker     break;
2008*9880d681SAndroid Build Coastguard Worker   }
2009*9880d681SAndroid Build Coastguard Worker 
2010*9880d681SAndroid Build Coastguard Worker   // Strip off any constant offsets so that we can reason about them.
2011*9880d681SAndroid Build Coastguard Worker   // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2012*9880d681SAndroid Build Coastguard Worker   // here and compare base addresses like AliasAnalysis does, however there are
2013*9880d681SAndroid Build Coastguard Worker   // numerous hazards. AliasAnalysis and its utilities rely on special rules
2014*9880d681SAndroid Build Coastguard Worker   // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2015*9880d681SAndroid Build Coastguard Worker   // doesn't need to guarantee pointer inequality when it says NoAlias.
2016*9880d681SAndroid Build Coastguard Worker   Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2017*9880d681SAndroid Build Coastguard Worker   Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
2018*9880d681SAndroid Build Coastguard Worker 
2019*9880d681SAndroid Build Coastguard Worker   // If LHS and RHS are related via constant offsets to the same base
2020*9880d681SAndroid Build Coastguard Worker   // value, we can replace it with an icmp which just compares the offsets.
2021*9880d681SAndroid Build Coastguard Worker   if (LHS == RHS)
2022*9880d681SAndroid Build Coastguard Worker     return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
2023*9880d681SAndroid Build Coastguard Worker 
2024*9880d681SAndroid Build Coastguard Worker   // Various optimizations for (in)equality comparisons.
2025*9880d681SAndroid Build Coastguard Worker   if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2026*9880d681SAndroid Build Coastguard Worker     // Different non-empty allocations that exist at the same time have
2027*9880d681SAndroid Build Coastguard Worker     // different addresses (if the program can tell). Global variables always
2028*9880d681SAndroid Build Coastguard Worker     // exist, so they always exist during the lifetime of each other and all
2029*9880d681SAndroid Build Coastguard Worker     // allocas. Two different allocas usually have different addresses...
2030*9880d681SAndroid Build Coastguard Worker     //
2031*9880d681SAndroid Build Coastguard Worker     // However, if there's an @llvm.stackrestore dynamically in between two
2032*9880d681SAndroid Build Coastguard Worker     // allocas, they may have the same address. It's tempting to reduce the
2033*9880d681SAndroid Build Coastguard Worker     // scope of the problem by only looking at *static* allocas here. That would
2034*9880d681SAndroid Build Coastguard Worker     // cover the majority of allocas while significantly reducing the likelihood
2035*9880d681SAndroid Build Coastguard Worker     // of having an @llvm.stackrestore pop up in the middle. However, it's not
2036*9880d681SAndroid Build Coastguard Worker     // actually impossible for an @llvm.stackrestore to pop up in the middle of
2037*9880d681SAndroid Build Coastguard Worker     // an entry block. Also, if we have a block that's not attached to a
2038*9880d681SAndroid Build Coastguard Worker     // function, we can't tell if it's "static" under the current definition.
2039*9880d681SAndroid Build Coastguard Worker     // Theoretically, this problem could be fixed by creating a new kind of
2040*9880d681SAndroid Build Coastguard Worker     // instruction kind specifically for static allocas. Such a new instruction
2041*9880d681SAndroid Build Coastguard Worker     // could be required to be at the top of the entry block, thus preventing it
2042*9880d681SAndroid Build Coastguard Worker     // from being subject to a @llvm.stackrestore. Instcombine could even
2043*9880d681SAndroid Build Coastguard Worker     // convert regular allocas into these special allocas. It'd be nifty.
2044*9880d681SAndroid Build Coastguard Worker     // However, until then, this problem remains open.
2045*9880d681SAndroid Build Coastguard Worker     //
2046*9880d681SAndroid Build Coastguard Worker     // So, we'll assume that two non-empty allocas have different addresses
2047*9880d681SAndroid Build Coastguard Worker     // for now.
2048*9880d681SAndroid Build Coastguard Worker     //
2049*9880d681SAndroid Build Coastguard Worker     // With all that, if the offsets are within the bounds of their allocations
2050*9880d681SAndroid Build Coastguard Worker     // (and not one-past-the-end! so we can't use inbounds!), and their
2051*9880d681SAndroid Build Coastguard Worker     // allocations aren't the same, the pointers are not equal.
2052*9880d681SAndroid Build Coastguard Worker     //
2053*9880d681SAndroid Build Coastguard Worker     // Note that it's not necessary to check for LHS being a global variable
2054*9880d681SAndroid Build Coastguard Worker     // address, due to canonicalization and constant folding.
2055*9880d681SAndroid Build Coastguard Worker     if (isa<AllocaInst>(LHS) &&
2056*9880d681SAndroid Build Coastguard Worker         (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
2057*9880d681SAndroid Build Coastguard Worker       ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2058*9880d681SAndroid Build Coastguard Worker       ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
2059*9880d681SAndroid Build Coastguard Worker       uint64_t LHSSize, RHSSize;
2060*9880d681SAndroid Build Coastguard Worker       if (LHSOffsetCI && RHSOffsetCI &&
2061*9880d681SAndroid Build Coastguard Worker           getObjectSize(LHS, LHSSize, DL, TLI) &&
2062*9880d681SAndroid Build Coastguard Worker           getObjectSize(RHS, RHSSize, DL, TLI)) {
2063*9880d681SAndroid Build Coastguard Worker         const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2064*9880d681SAndroid Build Coastguard Worker         const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
2065*9880d681SAndroid Build Coastguard Worker         if (!LHSOffsetValue.isNegative() &&
2066*9880d681SAndroid Build Coastguard Worker             !RHSOffsetValue.isNegative() &&
2067*9880d681SAndroid Build Coastguard Worker             LHSOffsetValue.ult(LHSSize) &&
2068*9880d681SAndroid Build Coastguard Worker             RHSOffsetValue.ult(RHSSize)) {
2069*9880d681SAndroid Build Coastguard Worker           return ConstantInt::get(GetCompareTy(LHS),
2070*9880d681SAndroid Build Coastguard Worker                                   !CmpInst::isTrueWhenEqual(Pred));
2071*9880d681SAndroid Build Coastguard Worker         }
2072*9880d681SAndroid Build Coastguard Worker       }
2073*9880d681SAndroid Build Coastguard Worker 
2074*9880d681SAndroid Build Coastguard Worker       // Repeat the above check but this time without depending on DataLayout
2075*9880d681SAndroid Build Coastguard Worker       // or being able to compute a precise size.
2076*9880d681SAndroid Build Coastguard Worker       if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2077*9880d681SAndroid Build Coastguard Worker           !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2078*9880d681SAndroid Build Coastguard Worker           LHSOffset->isNullValue() &&
2079*9880d681SAndroid Build Coastguard Worker           RHSOffset->isNullValue())
2080*9880d681SAndroid Build Coastguard Worker         return ConstantInt::get(GetCompareTy(LHS),
2081*9880d681SAndroid Build Coastguard Worker                                 !CmpInst::isTrueWhenEqual(Pred));
2082*9880d681SAndroid Build Coastguard Worker     }
2083*9880d681SAndroid Build Coastguard Worker 
2084*9880d681SAndroid Build Coastguard Worker     // Even if an non-inbounds GEP occurs along the path we can still optimize
2085*9880d681SAndroid Build Coastguard Worker     // equality comparisons concerning the result. We avoid walking the whole
2086*9880d681SAndroid Build Coastguard Worker     // chain again by starting where the last calls to
2087*9880d681SAndroid Build Coastguard Worker     // stripAndComputeConstantOffsets left off and accumulate the offsets.
2088*9880d681SAndroid Build Coastguard Worker     Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2089*9880d681SAndroid Build Coastguard Worker     Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
2090*9880d681SAndroid Build Coastguard Worker     if (LHS == RHS)
2091*9880d681SAndroid Build Coastguard Worker       return ConstantExpr::getICmp(Pred,
2092*9880d681SAndroid Build Coastguard Worker                                    ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2093*9880d681SAndroid Build Coastguard Worker                                    ConstantExpr::getAdd(RHSOffset, RHSNoBound));
2094*9880d681SAndroid Build Coastguard Worker 
2095*9880d681SAndroid Build Coastguard Worker     // If one side of the equality comparison must come from a noalias call
2096*9880d681SAndroid Build Coastguard Worker     // (meaning a system memory allocation function), and the other side must
2097*9880d681SAndroid Build Coastguard Worker     // come from a pointer that cannot overlap with dynamically-allocated
2098*9880d681SAndroid Build Coastguard Worker     // memory within the lifetime of the current function (allocas, byval
2099*9880d681SAndroid Build Coastguard Worker     // arguments, globals), then determine the comparison result here.
2100*9880d681SAndroid Build Coastguard Worker     SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2101*9880d681SAndroid Build Coastguard Worker     GetUnderlyingObjects(LHS, LHSUObjs, DL);
2102*9880d681SAndroid Build Coastguard Worker     GetUnderlyingObjects(RHS, RHSUObjs, DL);
2103*9880d681SAndroid Build Coastguard Worker 
2104*9880d681SAndroid Build Coastguard Worker     // Is the set of underlying objects all noalias calls?
2105*9880d681SAndroid Build Coastguard Worker     auto IsNAC = [](SmallVectorImpl<Value *> &Objects) {
2106*9880d681SAndroid Build Coastguard Worker       return std::all_of(Objects.begin(), Objects.end(), isNoAliasCall);
2107*9880d681SAndroid Build Coastguard Worker     };
2108*9880d681SAndroid Build Coastguard Worker 
2109*9880d681SAndroid Build Coastguard Worker     // Is the set of underlying objects all things which must be disjoint from
2110*9880d681SAndroid Build Coastguard Worker     // noalias calls. For allocas, we consider only static ones (dynamic
2111*9880d681SAndroid Build Coastguard Worker     // allocas might be transformed into calls to malloc not simultaneously
2112*9880d681SAndroid Build Coastguard Worker     // live with the compared-to allocation). For globals, we exclude symbols
2113*9880d681SAndroid Build Coastguard Worker     // that might be resolve lazily to symbols in another dynamically-loaded
2114*9880d681SAndroid Build Coastguard Worker     // library (and, thus, could be malloc'ed by the implementation).
2115*9880d681SAndroid Build Coastguard Worker     auto IsAllocDisjoint = [](SmallVectorImpl<Value *> &Objects) {
2116*9880d681SAndroid Build Coastguard Worker       return std::all_of(Objects.begin(), Objects.end(), [](Value *V) {
2117*9880d681SAndroid Build Coastguard Worker         if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2118*9880d681SAndroid Build Coastguard Worker           return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2119*9880d681SAndroid Build Coastguard Worker         if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2120*9880d681SAndroid Build Coastguard Worker           return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
2121*9880d681SAndroid Build Coastguard Worker                   GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
2122*9880d681SAndroid Build Coastguard Worker                  !GV->isThreadLocal();
2123*9880d681SAndroid Build Coastguard Worker         if (const Argument *A = dyn_cast<Argument>(V))
2124*9880d681SAndroid Build Coastguard Worker           return A->hasByValAttr();
2125*9880d681SAndroid Build Coastguard Worker         return false;
2126*9880d681SAndroid Build Coastguard Worker       });
2127*9880d681SAndroid Build Coastguard Worker     };
2128*9880d681SAndroid Build Coastguard Worker 
2129*9880d681SAndroid Build Coastguard Worker     if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2130*9880d681SAndroid Build Coastguard Worker         (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2131*9880d681SAndroid Build Coastguard Worker         return ConstantInt::get(GetCompareTy(LHS),
2132*9880d681SAndroid Build Coastguard Worker                                 !CmpInst::isTrueWhenEqual(Pred));
2133*9880d681SAndroid Build Coastguard Worker 
2134*9880d681SAndroid Build Coastguard Worker     // Fold comparisons for non-escaping pointer even if the allocation call
2135*9880d681SAndroid Build Coastguard Worker     // cannot be elided. We cannot fold malloc comparison to null. Also, the
2136*9880d681SAndroid Build Coastguard Worker     // dynamic allocation call could be either of the operands.
2137*9880d681SAndroid Build Coastguard Worker     Value *MI = nullptr;
2138*9880d681SAndroid Build Coastguard Worker     if (isAllocLikeFn(LHS, TLI) && llvm::isKnownNonNullAt(RHS, CxtI, DT))
2139*9880d681SAndroid Build Coastguard Worker       MI = LHS;
2140*9880d681SAndroid Build Coastguard Worker     else if (isAllocLikeFn(RHS, TLI) && llvm::isKnownNonNullAt(LHS, CxtI, DT))
2141*9880d681SAndroid Build Coastguard Worker       MI = RHS;
2142*9880d681SAndroid Build Coastguard Worker     // FIXME: We should also fold the compare when the pointer escapes, but the
2143*9880d681SAndroid Build Coastguard Worker     // compare dominates the pointer escape
2144*9880d681SAndroid Build Coastguard Worker     if (MI && !PointerMayBeCaptured(MI, true, true))
2145*9880d681SAndroid Build Coastguard Worker       return ConstantInt::get(GetCompareTy(LHS),
2146*9880d681SAndroid Build Coastguard Worker                               CmpInst::isFalseWhenEqual(Pred));
2147*9880d681SAndroid Build Coastguard Worker   }
2148*9880d681SAndroid Build Coastguard Worker 
2149*9880d681SAndroid Build Coastguard Worker   // Otherwise, fail.
2150*9880d681SAndroid Build Coastguard Worker   return nullptr;
2151*9880d681SAndroid Build Coastguard Worker }
2152*9880d681SAndroid Build Coastguard Worker 
2153*9880d681SAndroid Build Coastguard Worker /// Given operands for an ICmpInst, see if we can fold the result.
2154*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifyICmpInst(unsigned Predicate,Value * LHS,Value * RHS,const Query & Q,unsigned MaxRecurse)2155*9880d681SAndroid Build Coastguard Worker static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2156*9880d681SAndroid Build Coastguard Worker                                const Query &Q, unsigned MaxRecurse) {
2157*9880d681SAndroid Build Coastguard Worker   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2158*9880d681SAndroid Build Coastguard Worker   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
2159*9880d681SAndroid Build Coastguard Worker 
2160*9880d681SAndroid Build Coastguard Worker   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2161*9880d681SAndroid Build Coastguard Worker     if (Constant *CRHS = dyn_cast<Constant>(RHS))
2162*9880d681SAndroid Build Coastguard Worker       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
2163*9880d681SAndroid Build Coastguard Worker 
2164*9880d681SAndroid Build Coastguard Worker     // If we have a constant, make sure it is on the RHS.
2165*9880d681SAndroid Build Coastguard Worker     std::swap(LHS, RHS);
2166*9880d681SAndroid Build Coastguard Worker     Pred = CmpInst::getSwappedPredicate(Pred);
2167*9880d681SAndroid Build Coastguard Worker   }
2168*9880d681SAndroid Build Coastguard Worker 
2169*9880d681SAndroid Build Coastguard Worker   Type *ITy = GetCompareTy(LHS); // The return type.
2170*9880d681SAndroid Build Coastguard Worker   Type *OpTy = LHS->getType();   // The operand type.
2171*9880d681SAndroid Build Coastguard Worker 
2172*9880d681SAndroid Build Coastguard Worker   // icmp X, X -> true/false
2173*9880d681SAndroid Build Coastguard Worker   // X icmp undef -> true/false.  For example, icmp ugt %X, undef -> false
2174*9880d681SAndroid Build Coastguard Worker   // because X could be 0.
2175*9880d681SAndroid Build Coastguard Worker   if (LHS == RHS || isa<UndefValue>(RHS))
2176*9880d681SAndroid Build Coastguard Worker     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
2177*9880d681SAndroid Build Coastguard Worker 
2178*9880d681SAndroid Build Coastguard Worker   // Special case logic when the operands have i1 type.
2179*9880d681SAndroid Build Coastguard Worker   if (OpTy->getScalarType()->isIntegerTy(1)) {
2180*9880d681SAndroid Build Coastguard Worker     switch (Pred) {
2181*9880d681SAndroid Build Coastguard Worker     default: break;
2182*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_EQ:
2183*9880d681SAndroid Build Coastguard Worker       // X == 1 -> X
2184*9880d681SAndroid Build Coastguard Worker       if (match(RHS, m_One()))
2185*9880d681SAndroid Build Coastguard Worker         return LHS;
2186*9880d681SAndroid Build Coastguard Worker       break;
2187*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_NE:
2188*9880d681SAndroid Build Coastguard Worker       // X != 0 -> X
2189*9880d681SAndroid Build Coastguard Worker       if (match(RHS, m_Zero()))
2190*9880d681SAndroid Build Coastguard Worker         return LHS;
2191*9880d681SAndroid Build Coastguard Worker       break;
2192*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_UGT:
2193*9880d681SAndroid Build Coastguard Worker       // X >u 0 -> X
2194*9880d681SAndroid Build Coastguard Worker       if (match(RHS, m_Zero()))
2195*9880d681SAndroid Build Coastguard Worker         return LHS;
2196*9880d681SAndroid Build Coastguard Worker       break;
2197*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_UGE: {
2198*9880d681SAndroid Build Coastguard Worker       // X >=u 1 -> X
2199*9880d681SAndroid Build Coastguard Worker       if (match(RHS, m_One()))
2200*9880d681SAndroid Build Coastguard Worker         return LHS;
2201*9880d681SAndroid Build Coastguard Worker       if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2202*9880d681SAndroid Build Coastguard Worker         return getTrue(ITy);
2203*9880d681SAndroid Build Coastguard Worker       break;
2204*9880d681SAndroid Build Coastguard Worker     }
2205*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SGE: {
2206*9880d681SAndroid Build Coastguard Worker       /// For signed comparison, the values for an i1 are 0 and -1
2207*9880d681SAndroid Build Coastguard Worker       /// respectively. This maps into a truth table of:
2208*9880d681SAndroid Build Coastguard Worker       /// LHS | RHS | LHS >=s RHS   | LHS implies RHS
2209*9880d681SAndroid Build Coastguard Worker       ///  0  |  0  |  1 (0 >= 0)   |  1
2210*9880d681SAndroid Build Coastguard Worker       ///  0  |  1  |  1 (0 >= -1)  |  1
2211*9880d681SAndroid Build Coastguard Worker       ///  1  |  0  |  0 (-1 >= 0)  |  0
2212*9880d681SAndroid Build Coastguard Worker       ///  1  |  1  |  1 (-1 >= -1) |  1
2213*9880d681SAndroid Build Coastguard Worker       if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2214*9880d681SAndroid Build Coastguard Worker         return getTrue(ITy);
2215*9880d681SAndroid Build Coastguard Worker       break;
2216*9880d681SAndroid Build Coastguard Worker     }
2217*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SLT:
2218*9880d681SAndroid Build Coastguard Worker       // X <s 0 -> X
2219*9880d681SAndroid Build Coastguard Worker       if (match(RHS, m_Zero()))
2220*9880d681SAndroid Build Coastguard Worker         return LHS;
2221*9880d681SAndroid Build Coastguard Worker       break;
2222*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SLE:
2223*9880d681SAndroid Build Coastguard Worker       // X <=s -1 -> X
2224*9880d681SAndroid Build Coastguard Worker       if (match(RHS, m_One()))
2225*9880d681SAndroid Build Coastguard Worker         return LHS;
2226*9880d681SAndroid Build Coastguard Worker       break;
2227*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_ULE: {
2228*9880d681SAndroid Build Coastguard Worker       if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2229*9880d681SAndroid Build Coastguard Worker         return getTrue(ITy);
2230*9880d681SAndroid Build Coastguard Worker       break;
2231*9880d681SAndroid Build Coastguard Worker     }
2232*9880d681SAndroid Build Coastguard Worker     }
2233*9880d681SAndroid Build Coastguard Worker   }
2234*9880d681SAndroid Build Coastguard Worker 
2235*9880d681SAndroid Build Coastguard Worker   // If we are comparing with zero then try hard since this is a common case.
2236*9880d681SAndroid Build Coastguard Worker   if (match(RHS, m_Zero())) {
2237*9880d681SAndroid Build Coastguard Worker     bool LHSKnownNonNegative, LHSKnownNegative;
2238*9880d681SAndroid Build Coastguard Worker     switch (Pred) {
2239*9880d681SAndroid Build Coastguard Worker     default: llvm_unreachable("Unknown ICmp predicate!");
2240*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_ULT:
2241*9880d681SAndroid Build Coastguard Worker       return getFalse(ITy);
2242*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_UGE:
2243*9880d681SAndroid Build Coastguard Worker       return getTrue(ITy);
2244*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_EQ:
2245*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_ULE:
2246*9880d681SAndroid Build Coastguard Worker       if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2247*9880d681SAndroid Build Coastguard Worker         return getFalse(ITy);
2248*9880d681SAndroid Build Coastguard Worker       break;
2249*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_NE:
2250*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_UGT:
2251*9880d681SAndroid Build Coastguard Worker       if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2252*9880d681SAndroid Build Coastguard Worker         return getTrue(ITy);
2253*9880d681SAndroid Build Coastguard Worker       break;
2254*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SLT:
2255*9880d681SAndroid Build Coastguard Worker       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2256*9880d681SAndroid Build Coastguard Worker                      Q.CxtI, Q.DT);
2257*9880d681SAndroid Build Coastguard Worker       if (LHSKnownNegative)
2258*9880d681SAndroid Build Coastguard Worker         return getTrue(ITy);
2259*9880d681SAndroid Build Coastguard Worker       if (LHSKnownNonNegative)
2260*9880d681SAndroid Build Coastguard Worker         return getFalse(ITy);
2261*9880d681SAndroid Build Coastguard Worker       break;
2262*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SLE:
2263*9880d681SAndroid Build Coastguard Worker       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2264*9880d681SAndroid Build Coastguard Worker                      Q.CxtI, Q.DT);
2265*9880d681SAndroid Build Coastguard Worker       if (LHSKnownNegative)
2266*9880d681SAndroid Build Coastguard Worker         return getTrue(ITy);
2267*9880d681SAndroid Build Coastguard Worker       if (LHSKnownNonNegative &&
2268*9880d681SAndroid Build Coastguard Worker           isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2269*9880d681SAndroid Build Coastguard Worker         return getFalse(ITy);
2270*9880d681SAndroid Build Coastguard Worker       break;
2271*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SGE:
2272*9880d681SAndroid Build Coastguard Worker       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2273*9880d681SAndroid Build Coastguard Worker                      Q.CxtI, Q.DT);
2274*9880d681SAndroid Build Coastguard Worker       if (LHSKnownNegative)
2275*9880d681SAndroid Build Coastguard Worker         return getFalse(ITy);
2276*9880d681SAndroid Build Coastguard Worker       if (LHSKnownNonNegative)
2277*9880d681SAndroid Build Coastguard Worker         return getTrue(ITy);
2278*9880d681SAndroid Build Coastguard Worker       break;
2279*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SGT:
2280*9880d681SAndroid Build Coastguard Worker       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2281*9880d681SAndroid Build Coastguard Worker                      Q.CxtI, Q.DT);
2282*9880d681SAndroid Build Coastguard Worker       if (LHSKnownNegative)
2283*9880d681SAndroid Build Coastguard Worker         return getFalse(ITy);
2284*9880d681SAndroid Build Coastguard Worker       if (LHSKnownNonNegative &&
2285*9880d681SAndroid Build Coastguard Worker           isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2286*9880d681SAndroid Build Coastguard Worker         return getTrue(ITy);
2287*9880d681SAndroid Build Coastguard Worker       break;
2288*9880d681SAndroid Build Coastguard Worker     }
2289*9880d681SAndroid Build Coastguard Worker   }
2290*9880d681SAndroid Build Coastguard Worker 
2291*9880d681SAndroid Build Coastguard Worker   // See if we are doing a comparison with a constant integer.
2292*9880d681SAndroid Build Coastguard Worker   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2293*9880d681SAndroid Build Coastguard Worker     // Rule out tautological comparisons (eg., ult 0 or uge 0).
2294*9880d681SAndroid Build Coastguard Worker     ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
2295*9880d681SAndroid Build Coastguard Worker     if (RHS_CR.isEmptySet())
2296*9880d681SAndroid Build Coastguard Worker       return ConstantInt::getFalse(CI->getContext());
2297*9880d681SAndroid Build Coastguard Worker     if (RHS_CR.isFullSet())
2298*9880d681SAndroid Build Coastguard Worker       return ConstantInt::getTrue(CI->getContext());
2299*9880d681SAndroid Build Coastguard Worker 
2300*9880d681SAndroid Build Coastguard Worker     // Many binary operators with constant RHS have easy to compute constant
2301*9880d681SAndroid Build Coastguard Worker     // range.  Use them to check whether the comparison is a tautology.
2302*9880d681SAndroid Build Coastguard Worker     unsigned Width = CI->getBitWidth();
2303*9880d681SAndroid Build Coastguard Worker     APInt Lower = APInt(Width, 0);
2304*9880d681SAndroid Build Coastguard Worker     APInt Upper = APInt(Width, 0);
2305*9880d681SAndroid Build Coastguard Worker     ConstantInt *CI2;
2306*9880d681SAndroid Build Coastguard Worker     if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
2307*9880d681SAndroid Build Coastguard Worker       // 'urem x, CI2' produces [0, CI2).
2308*9880d681SAndroid Build Coastguard Worker       Upper = CI2->getValue();
2309*9880d681SAndroid Build Coastguard Worker     } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
2310*9880d681SAndroid Build Coastguard Worker       // 'srem x, CI2' produces (-|CI2|, |CI2|).
2311*9880d681SAndroid Build Coastguard Worker       Upper = CI2->getValue().abs();
2312*9880d681SAndroid Build Coastguard Worker       Lower = (-Upper) + 1;
2313*9880d681SAndroid Build Coastguard Worker     } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
2314*9880d681SAndroid Build Coastguard Worker       // 'udiv CI2, x' produces [0, CI2].
2315*9880d681SAndroid Build Coastguard Worker       Upper = CI2->getValue() + 1;
2316*9880d681SAndroid Build Coastguard Worker     } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
2317*9880d681SAndroid Build Coastguard Worker       // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
2318*9880d681SAndroid Build Coastguard Worker       APInt NegOne = APInt::getAllOnesValue(Width);
2319*9880d681SAndroid Build Coastguard Worker       if (!CI2->isZero())
2320*9880d681SAndroid Build Coastguard Worker         Upper = NegOne.udiv(CI2->getValue()) + 1;
2321*9880d681SAndroid Build Coastguard Worker     } else if (match(LHS, m_SDiv(m_ConstantInt(CI2), m_Value()))) {
2322*9880d681SAndroid Build Coastguard Worker       if (CI2->isMinSignedValue()) {
2323*9880d681SAndroid Build Coastguard Worker         // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2324*9880d681SAndroid Build Coastguard Worker         Lower = CI2->getValue();
2325*9880d681SAndroid Build Coastguard Worker         Upper = Lower.lshr(1) + 1;
2326*9880d681SAndroid Build Coastguard Worker       } else {
2327*9880d681SAndroid Build Coastguard Worker         // 'sdiv CI2, x' produces [-|CI2|, |CI2|].
2328*9880d681SAndroid Build Coastguard Worker         Upper = CI2->getValue().abs() + 1;
2329*9880d681SAndroid Build Coastguard Worker         Lower = (-Upper) + 1;
2330*9880d681SAndroid Build Coastguard Worker       }
2331*9880d681SAndroid Build Coastguard Worker     } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
2332*9880d681SAndroid Build Coastguard Worker       APInt IntMin = APInt::getSignedMinValue(Width);
2333*9880d681SAndroid Build Coastguard Worker       APInt IntMax = APInt::getSignedMaxValue(Width);
2334*9880d681SAndroid Build Coastguard Worker       const APInt &Val = CI2->getValue();
2335*9880d681SAndroid Build Coastguard Worker       if (Val.isAllOnesValue()) {
2336*9880d681SAndroid Build Coastguard Worker         // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2337*9880d681SAndroid Build Coastguard Worker         //    where CI2 != -1 and CI2 != 0 and CI2 != 1
2338*9880d681SAndroid Build Coastguard Worker         Lower = IntMin + 1;
2339*9880d681SAndroid Build Coastguard Worker         Upper = IntMax + 1;
2340*9880d681SAndroid Build Coastguard Worker       } else if (Val.countLeadingZeros() < Width - 1) {
2341*9880d681SAndroid Build Coastguard Worker         // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2]
2342*9880d681SAndroid Build Coastguard Worker         //    where CI2 != -1 and CI2 != 0 and CI2 != 1
2343*9880d681SAndroid Build Coastguard Worker         Lower = IntMin.sdiv(Val);
2344*9880d681SAndroid Build Coastguard Worker         Upper = IntMax.sdiv(Val);
2345*9880d681SAndroid Build Coastguard Worker         if (Lower.sgt(Upper))
2346*9880d681SAndroid Build Coastguard Worker           std::swap(Lower, Upper);
2347*9880d681SAndroid Build Coastguard Worker         Upper = Upper + 1;
2348*9880d681SAndroid Build Coastguard Worker         assert(Upper != Lower && "Upper part of range has wrapped!");
2349*9880d681SAndroid Build Coastguard Worker       }
2350*9880d681SAndroid Build Coastguard Worker     } else if (match(LHS, m_NUWShl(m_ConstantInt(CI2), m_Value()))) {
2351*9880d681SAndroid Build Coastguard Worker       // 'shl nuw CI2, x' produces [CI2, CI2 << CLZ(CI2)]
2352*9880d681SAndroid Build Coastguard Worker       Lower = CI2->getValue();
2353*9880d681SAndroid Build Coastguard Worker       Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2354*9880d681SAndroid Build Coastguard Worker     } else if (match(LHS, m_NSWShl(m_ConstantInt(CI2), m_Value()))) {
2355*9880d681SAndroid Build Coastguard Worker       if (CI2->isNegative()) {
2356*9880d681SAndroid Build Coastguard Worker         // 'shl nsw CI2, x' produces [CI2 << CLO(CI2)-1, CI2]
2357*9880d681SAndroid Build Coastguard Worker         unsigned ShiftAmount = CI2->getValue().countLeadingOnes() - 1;
2358*9880d681SAndroid Build Coastguard Worker         Lower = CI2->getValue().shl(ShiftAmount);
2359*9880d681SAndroid Build Coastguard Worker         Upper = CI2->getValue() + 1;
2360*9880d681SAndroid Build Coastguard Worker       } else {
2361*9880d681SAndroid Build Coastguard Worker         // 'shl nsw CI2, x' produces [CI2, CI2 << CLZ(CI2)-1]
2362*9880d681SAndroid Build Coastguard Worker         unsigned ShiftAmount = CI2->getValue().countLeadingZeros() - 1;
2363*9880d681SAndroid Build Coastguard Worker         Lower = CI2->getValue();
2364*9880d681SAndroid Build Coastguard Worker         Upper = CI2->getValue().shl(ShiftAmount) + 1;
2365*9880d681SAndroid Build Coastguard Worker       }
2366*9880d681SAndroid Build Coastguard Worker     } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
2367*9880d681SAndroid Build Coastguard Worker       // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
2368*9880d681SAndroid Build Coastguard Worker       APInt NegOne = APInt::getAllOnesValue(Width);
2369*9880d681SAndroid Build Coastguard Worker       if (CI2->getValue().ult(Width))
2370*9880d681SAndroid Build Coastguard Worker         Upper = NegOne.lshr(CI2->getValue()) + 1;
2371*9880d681SAndroid Build Coastguard Worker     } else if (match(LHS, m_LShr(m_ConstantInt(CI2), m_Value()))) {
2372*9880d681SAndroid Build Coastguard Worker       // 'lshr CI2, x' produces [CI2 >> (Width-1), CI2].
2373*9880d681SAndroid Build Coastguard Worker       unsigned ShiftAmount = Width - 1;
2374*9880d681SAndroid Build Coastguard Worker       if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2375*9880d681SAndroid Build Coastguard Worker         ShiftAmount = CI2->getValue().countTrailingZeros();
2376*9880d681SAndroid Build Coastguard Worker       Lower = CI2->getValue().lshr(ShiftAmount);
2377*9880d681SAndroid Build Coastguard Worker       Upper = CI2->getValue() + 1;
2378*9880d681SAndroid Build Coastguard Worker     } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
2379*9880d681SAndroid Build Coastguard Worker       // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
2380*9880d681SAndroid Build Coastguard Worker       APInt IntMin = APInt::getSignedMinValue(Width);
2381*9880d681SAndroid Build Coastguard Worker       APInt IntMax = APInt::getSignedMaxValue(Width);
2382*9880d681SAndroid Build Coastguard Worker       if (CI2->getValue().ult(Width)) {
2383*9880d681SAndroid Build Coastguard Worker         Lower = IntMin.ashr(CI2->getValue());
2384*9880d681SAndroid Build Coastguard Worker         Upper = IntMax.ashr(CI2->getValue()) + 1;
2385*9880d681SAndroid Build Coastguard Worker       }
2386*9880d681SAndroid Build Coastguard Worker     } else if (match(LHS, m_AShr(m_ConstantInt(CI2), m_Value()))) {
2387*9880d681SAndroid Build Coastguard Worker       unsigned ShiftAmount = Width - 1;
2388*9880d681SAndroid Build Coastguard Worker       if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2389*9880d681SAndroid Build Coastguard Worker         ShiftAmount = CI2->getValue().countTrailingZeros();
2390*9880d681SAndroid Build Coastguard Worker       if (CI2->isNegative()) {
2391*9880d681SAndroid Build Coastguard Worker         // 'ashr CI2, x' produces [CI2, CI2 >> (Width-1)]
2392*9880d681SAndroid Build Coastguard Worker         Lower = CI2->getValue();
2393*9880d681SAndroid Build Coastguard Worker         Upper = CI2->getValue().ashr(ShiftAmount) + 1;
2394*9880d681SAndroid Build Coastguard Worker       } else {
2395*9880d681SAndroid Build Coastguard Worker         // 'ashr CI2, x' produces [CI2 >> (Width-1), CI2]
2396*9880d681SAndroid Build Coastguard Worker         Lower = CI2->getValue().ashr(ShiftAmount);
2397*9880d681SAndroid Build Coastguard Worker         Upper = CI2->getValue() + 1;
2398*9880d681SAndroid Build Coastguard Worker       }
2399*9880d681SAndroid Build Coastguard Worker     } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
2400*9880d681SAndroid Build Coastguard Worker       // 'or x, CI2' produces [CI2, UINT_MAX].
2401*9880d681SAndroid Build Coastguard Worker       Lower = CI2->getValue();
2402*9880d681SAndroid Build Coastguard Worker     } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
2403*9880d681SAndroid Build Coastguard Worker       // 'and x, CI2' produces [0, CI2].
2404*9880d681SAndroid Build Coastguard Worker       Upper = CI2->getValue() + 1;
2405*9880d681SAndroid Build Coastguard Worker     } else if (match(LHS, m_NUWAdd(m_Value(), m_ConstantInt(CI2)))) {
2406*9880d681SAndroid Build Coastguard Worker       // 'add nuw x, CI2' produces [CI2, UINT_MAX].
2407*9880d681SAndroid Build Coastguard Worker       Lower = CI2->getValue();
2408*9880d681SAndroid Build Coastguard Worker     }
2409*9880d681SAndroid Build Coastguard Worker 
2410*9880d681SAndroid Build Coastguard Worker     ConstantRange LHS_CR = Lower != Upper ? ConstantRange(Lower, Upper)
2411*9880d681SAndroid Build Coastguard Worker                                           : ConstantRange(Width, true);
2412*9880d681SAndroid Build Coastguard Worker 
2413*9880d681SAndroid Build Coastguard Worker     if (auto *I = dyn_cast<Instruction>(LHS))
2414*9880d681SAndroid Build Coastguard Worker       if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
2415*9880d681SAndroid Build Coastguard Worker         LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
2416*9880d681SAndroid Build Coastguard Worker 
2417*9880d681SAndroid Build Coastguard Worker     if (!LHS_CR.isFullSet()) {
2418*9880d681SAndroid Build Coastguard Worker       if (RHS_CR.contains(LHS_CR))
2419*9880d681SAndroid Build Coastguard Worker         return ConstantInt::getTrue(RHS->getContext());
2420*9880d681SAndroid Build Coastguard Worker       if (RHS_CR.inverse().contains(LHS_CR))
2421*9880d681SAndroid Build Coastguard Worker         return ConstantInt::getFalse(RHS->getContext());
2422*9880d681SAndroid Build Coastguard Worker     }
2423*9880d681SAndroid Build Coastguard Worker   }
2424*9880d681SAndroid Build Coastguard Worker 
2425*9880d681SAndroid Build Coastguard Worker   // If both operands have range metadata, use the metadata
2426*9880d681SAndroid Build Coastguard Worker   // to simplify the comparison.
2427*9880d681SAndroid Build Coastguard Worker   if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
2428*9880d681SAndroid Build Coastguard Worker     auto RHS_Instr = dyn_cast<Instruction>(RHS);
2429*9880d681SAndroid Build Coastguard Worker     auto LHS_Instr = dyn_cast<Instruction>(LHS);
2430*9880d681SAndroid Build Coastguard Worker 
2431*9880d681SAndroid Build Coastguard Worker     if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
2432*9880d681SAndroid Build Coastguard Worker         LHS_Instr->getMetadata(LLVMContext::MD_range)) {
2433*9880d681SAndroid Build Coastguard Worker       auto RHS_CR = getConstantRangeFromMetadata(
2434*9880d681SAndroid Build Coastguard Worker           *RHS_Instr->getMetadata(LLVMContext::MD_range));
2435*9880d681SAndroid Build Coastguard Worker       auto LHS_CR = getConstantRangeFromMetadata(
2436*9880d681SAndroid Build Coastguard Worker           *LHS_Instr->getMetadata(LLVMContext::MD_range));
2437*9880d681SAndroid Build Coastguard Worker 
2438*9880d681SAndroid Build Coastguard Worker       auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
2439*9880d681SAndroid Build Coastguard Worker       if (Satisfied_CR.contains(LHS_CR))
2440*9880d681SAndroid Build Coastguard Worker         return ConstantInt::getTrue(RHS->getContext());
2441*9880d681SAndroid Build Coastguard Worker 
2442*9880d681SAndroid Build Coastguard Worker       auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
2443*9880d681SAndroid Build Coastguard Worker                 CmpInst::getInversePredicate(Pred), RHS_CR);
2444*9880d681SAndroid Build Coastguard Worker       if (InversedSatisfied_CR.contains(LHS_CR))
2445*9880d681SAndroid Build Coastguard Worker         return ConstantInt::getFalse(RHS->getContext());
2446*9880d681SAndroid Build Coastguard Worker     }
2447*9880d681SAndroid Build Coastguard Worker   }
2448*9880d681SAndroid Build Coastguard Worker 
2449*9880d681SAndroid Build Coastguard Worker   // Compare of cast, for example (zext X) != 0 -> X != 0
2450*9880d681SAndroid Build Coastguard Worker   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2451*9880d681SAndroid Build Coastguard Worker     Instruction *LI = cast<CastInst>(LHS);
2452*9880d681SAndroid Build Coastguard Worker     Value *SrcOp = LI->getOperand(0);
2453*9880d681SAndroid Build Coastguard Worker     Type *SrcTy = SrcOp->getType();
2454*9880d681SAndroid Build Coastguard Worker     Type *DstTy = LI->getType();
2455*9880d681SAndroid Build Coastguard Worker 
2456*9880d681SAndroid Build Coastguard Worker     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2457*9880d681SAndroid Build Coastguard Worker     // if the integer type is the same size as the pointer type.
2458*9880d681SAndroid Build Coastguard Worker     if (MaxRecurse && isa<PtrToIntInst>(LI) &&
2459*9880d681SAndroid Build Coastguard Worker         Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
2460*9880d681SAndroid Build Coastguard Worker       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2461*9880d681SAndroid Build Coastguard Worker         // Transfer the cast to the constant.
2462*9880d681SAndroid Build Coastguard Worker         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2463*9880d681SAndroid Build Coastguard Worker                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
2464*9880d681SAndroid Build Coastguard Worker                                         Q, MaxRecurse-1))
2465*9880d681SAndroid Build Coastguard Worker           return V;
2466*9880d681SAndroid Build Coastguard Worker       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2467*9880d681SAndroid Build Coastguard Worker         if (RI->getOperand(0)->getType() == SrcTy)
2468*9880d681SAndroid Build Coastguard Worker           // Compare without the cast.
2469*9880d681SAndroid Build Coastguard Worker           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2470*9880d681SAndroid Build Coastguard Worker                                           Q, MaxRecurse-1))
2471*9880d681SAndroid Build Coastguard Worker             return V;
2472*9880d681SAndroid Build Coastguard Worker       }
2473*9880d681SAndroid Build Coastguard Worker     }
2474*9880d681SAndroid Build Coastguard Worker 
2475*9880d681SAndroid Build Coastguard Worker     if (isa<ZExtInst>(LHS)) {
2476*9880d681SAndroid Build Coastguard Worker       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2477*9880d681SAndroid Build Coastguard Worker       // same type.
2478*9880d681SAndroid Build Coastguard Worker       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2479*9880d681SAndroid Build Coastguard Worker         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2480*9880d681SAndroid Build Coastguard Worker           // Compare X and Y.  Note that signed predicates become unsigned.
2481*9880d681SAndroid Build Coastguard Worker           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2482*9880d681SAndroid Build Coastguard Worker                                           SrcOp, RI->getOperand(0), Q,
2483*9880d681SAndroid Build Coastguard Worker                                           MaxRecurse-1))
2484*9880d681SAndroid Build Coastguard Worker             return V;
2485*9880d681SAndroid Build Coastguard Worker       }
2486*9880d681SAndroid Build Coastguard Worker       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2487*9880d681SAndroid Build Coastguard Worker       // too.  If not, then try to deduce the result of the comparison.
2488*9880d681SAndroid Build Coastguard Worker       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2489*9880d681SAndroid Build Coastguard Worker         // Compute the constant that would happen if we truncated to SrcTy then
2490*9880d681SAndroid Build Coastguard Worker         // reextended to DstTy.
2491*9880d681SAndroid Build Coastguard Worker         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2492*9880d681SAndroid Build Coastguard Worker         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2493*9880d681SAndroid Build Coastguard Worker 
2494*9880d681SAndroid Build Coastguard Worker         // If the re-extended constant didn't change then this is effectively
2495*9880d681SAndroid Build Coastguard Worker         // also a case of comparing two zero-extended values.
2496*9880d681SAndroid Build Coastguard Worker         if (RExt == CI && MaxRecurse)
2497*9880d681SAndroid Build Coastguard Worker           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2498*9880d681SAndroid Build Coastguard Worker                                         SrcOp, Trunc, Q, MaxRecurse-1))
2499*9880d681SAndroid Build Coastguard Worker             return V;
2500*9880d681SAndroid Build Coastguard Worker 
2501*9880d681SAndroid Build Coastguard Worker         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2502*9880d681SAndroid Build Coastguard Worker         // there.  Use this to work out the result of the comparison.
2503*9880d681SAndroid Build Coastguard Worker         if (RExt != CI) {
2504*9880d681SAndroid Build Coastguard Worker           switch (Pred) {
2505*9880d681SAndroid Build Coastguard Worker           default: llvm_unreachable("Unknown ICmp predicate!");
2506*9880d681SAndroid Build Coastguard Worker           // LHS <u RHS.
2507*9880d681SAndroid Build Coastguard Worker           case ICmpInst::ICMP_EQ:
2508*9880d681SAndroid Build Coastguard Worker           case ICmpInst::ICMP_UGT:
2509*9880d681SAndroid Build Coastguard Worker           case ICmpInst::ICMP_UGE:
2510*9880d681SAndroid Build Coastguard Worker             return ConstantInt::getFalse(CI->getContext());
2511*9880d681SAndroid Build Coastguard Worker 
2512*9880d681SAndroid Build Coastguard Worker           case ICmpInst::ICMP_NE:
2513*9880d681SAndroid Build Coastguard Worker           case ICmpInst::ICMP_ULT:
2514*9880d681SAndroid Build Coastguard Worker           case ICmpInst::ICMP_ULE:
2515*9880d681SAndroid Build Coastguard Worker             return ConstantInt::getTrue(CI->getContext());
2516*9880d681SAndroid Build Coastguard Worker 
2517*9880d681SAndroid Build Coastguard Worker           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
2518*9880d681SAndroid Build Coastguard Worker           // is non-negative then LHS <s RHS.
2519*9880d681SAndroid Build Coastguard Worker           case ICmpInst::ICMP_SGT:
2520*9880d681SAndroid Build Coastguard Worker           case ICmpInst::ICMP_SGE:
2521*9880d681SAndroid Build Coastguard Worker             return CI->getValue().isNegative() ?
2522*9880d681SAndroid Build Coastguard Worker               ConstantInt::getTrue(CI->getContext()) :
2523*9880d681SAndroid Build Coastguard Worker               ConstantInt::getFalse(CI->getContext());
2524*9880d681SAndroid Build Coastguard Worker 
2525*9880d681SAndroid Build Coastguard Worker           case ICmpInst::ICMP_SLT:
2526*9880d681SAndroid Build Coastguard Worker           case ICmpInst::ICMP_SLE:
2527*9880d681SAndroid Build Coastguard Worker             return CI->getValue().isNegative() ?
2528*9880d681SAndroid Build Coastguard Worker               ConstantInt::getFalse(CI->getContext()) :
2529*9880d681SAndroid Build Coastguard Worker               ConstantInt::getTrue(CI->getContext());
2530*9880d681SAndroid Build Coastguard Worker           }
2531*9880d681SAndroid Build Coastguard Worker         }
2532*9880d681SAndroid Build Coastguard Worker       }
2533*9880d681SAndroid Build Coastguard Worker     }
2534*9880d681SAndroid Build Coastguard Worker 
2535*9880d681SAndroid Build Coastguard Worker     if (isa<SExtInst>(LHS)) {
2536*9880d681SAndroid Build Coastguard Worker       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2537*9880d681SAndroid Build Coastguard Worker       // same type.
2538*9880d681SAndroid Build Coastguard Worker       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2539*9880d681SAndroid Build Coastguard Worker         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2540*9880d681SAndroid Build Coastguard Worker           // Compare X and Y.  Note that the predicate does not change.
2541*9880d681SAndroid Build Coastguard Worker           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2542*9880d681SAndroid Build Coastguard Worker                                           Q, MaxRecurse-1))
2543*9880d681SAndroid Build Coastguard Worker             return V;
2544*9880d681SAndroid Build Coastguard Worker       }
2545*9880d681SAndroid Build Coastguard Worker       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2546*9880d681SAndroid Build Coastguard Worker       // too.  If not, then try to deduce the result of the comparison.
2547*9880d681SAndroid Build Coastguard Worker       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2548*9880d681SAndroid Build Coastguard Worker         // Compute the constant that would happen if we truncated to SrcTy then
2549*9880d681SAndroid Build Coastguard Worker         // reextended to DstTy.
2550*9880d681SAndroid Build Coastguard Worker         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2551*9880d681SAndroid Build Coastguard Worker         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2552*9880d681SAndroid Build Coastguard Worker 
2553*9880d681SAndroid Build Coastguard Worker         // If the re-extended constant didn't change then this is effectively
2554*9880d681SAndroid Build Coastguard Worker         // also a case of comparing two sign-extended values.
2555*9880d681SAndroid Build Coastguard Worker         if (RExt == CI && MaxRecurse)
2556*9880d681SAndroid Build Coastguard Worker           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
2557*9880d681SAndroid Build Coastguard Worker             return V;
2558*9880d681SAndroid Build Coastguard Worker 
2559*9880d681SAndroid Build Coastguard Worker         // Otherwise the upper bits of LHS are all equal, while RHS has varying
2560*9880d681SAndroid Build Coastguard Worker         // bits there.  Use this to work out the result of the comparison.
2561*9880d681SAndroid Build Coastguard Worker         if (RExt != CI) {
2562*9880d681SAndroid Build Coastguard Worker           switch (Pred) {
2563*9880d681SAndroid Build Coastguard Worker           default: llvm_unreachable("Unknown ICmp predicate!");
2564*9880d681SAndroid Build Coastguard Worker           case ICmpInst::ICMP_EQ:
2565*9880d681SAndroid Build Coastguard Worker             return ConstantInt::getFalse(CI->getContext());
2566*9880d681SAndroid Build Coastguard Worker           case ICmpInst::ICMP_NE:
2567*9880d681SAndroid Build Coastguard Worker             return ConstantInt::getTrue(CI->getContext());
2568*9880d681SAndroid Build Coastguard Worker 
2569*9880d681SAndroid Build Coastguard Worker           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
2570*9880d681SAndroid Build Coastguard Worker           // LHS >s RHS.
2571*9880d681SAndroid Build Coastguard Worker           case ICmpInst::ICMP_SGT:
2572*9880d681SAndroid Build Coastguard Worker           case ICmpInst::ICMP_SGE:
2573*9880d681SAndroid Build Coastguard Worker             return CI->getValue().isNegative() ?
2574*9880d681SAndroid Build Coastguard Worker               ConstantInt::getTrue(CI->getContext()) :
2575*9880d681SAndroid Build Coastguard Worker               ConstantInt::getFalse(CI->getContext());
2576*9880d681SAndroid Build Coastguard Worker           case ICmpInst::ICMP_SLT:
2577*9880d681SAndroid Build Coastguard Worker           case ICmpInst::ICMP_SLE:
2578*9880d681SAndroid Build Coastguard Worker             return CI->getValue().isNegative() ?
2579*9880d681SAndroid Build Coastguard Worker               ConstantInt::getFalse(CI->getContext()) :
2580*9880d681SAndroid Build Coastguard Worker               ConstantInt::getTrue(CI->getContext());
2581*9880d681SAndroid Build Coastguard Worker 
2582*9880d681SAndroid Build Coastguard Worker           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
2583*9880d681SAndroid Build Coastguard Worker           // LHS >u RHS.
2584*9880d681SAndroid Build Coastguard Worker           case ICmpInst::ICMP_UGT:
2585*9880d681SAndroid Build Coastguard Worker           case ICmpInst::ICMP_UGE:
2586*9880d681SAndroid Build Coastguard Worker             // Comparison is true iff the LHS <s 0.
2587*9880d681SAndroid Build Coastguard Worker             if (MaxRecurse)
2588*9880d681SAndroid Build Coastguard Worker               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2589*9880d681SAndroid Build Coastguard Worker                                               Constant::getNullValue(SrcTy),
2590*9880d681SAndroid Build Coastguard Worker                                               Q, MaxRecurse-1))
2591*9880d681SAndroid Build Coastguard Worker                 return V;
2592*9880d681SAndroid Build Coastguard Worker             break;
2593*9880d681SAndroid Build Coastguard Worker           case ICmpInst::ICMP_ULT:
2594*9880d681SAndroid Build Coastguard Worker           case ICmpInst::ICMP_ULE:
2595*9880d681SAndroid Build Coastguard Worker             // Comparison is true iff the LHS >=s 0.
2596*9880d681SAndroid Build Coastguard Worker             if (MaxRecurse)
2597*9880d681SAndroid Build Coastguard Worker               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2598*9880d681SAndroid Build Coastguard Worker                                               Constant::getNullValue(SrcTy),
2599*9880d681SAndroid Build Coastguard Worker                                               Q, MaxRecurse-1))
2600*9880d681SAndroid Build Coastguard Worker                 return V;
2601*9880d681SAndroid Build Coastguard Worker             break;
2602*9880d681SAndroid Build Coastguard Worker           }
2603*9880d681SAndroid Build Coastguard Worker         }
2604*9880d681SAndroid Build Coastguard Worker       }
2605*9880d681SAndroid Build Coastguard Worker     }
2606*9880d681SAndroid Build Coastguard Worker   }
2607*9880d681SAndroid Build Coastguard Worker 
2608*9880d681SAndroid Build Coastguard Worker   // icmp eq|ne X, Y -> false|true if X != Y
2609*9880d681SAndroid Build Coastguard Worker   if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2610*9880d681SAndroid Build Coastguard Worker       isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) {
2611*9880d681SAndroid Build Coastguard Worker     LLVMContext &Ctx = LHS->getType()->getContext();
2612*9880d681SAndroid Build Coastguard Worker     return Pred == ICmpInst::ICMP_NE ?
2613*9880d681SAndroid Build Coastguard Worker       ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
2614*9880d681SAndroid Build Coastguard Worker   }
2615*9880d681SAndroid Build Coastguard Worker 
2616*9880d681SAndroid Build Coastguard Worker   // Special logic for binary operators.
2617*9880d681SAndroid Build Coastguard Worker   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2618*9880d681SAndroid Build Coastguard Worker   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2619*9880d681SAndroid Build Coastguard Worker   if (MaxRecurse && (LBO || RBO)) {
2620*9880d681SAndroid Build Coastguard Worker     // Analyze the case when either LHS or RHS is an add instruction.
2621*9880d681SAndroid Build Coastguard Worker     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2622*9880d681SAndroid Build Coastguard Worker     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2623*9880d681SAndroid Build Coastguard Worker     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2624*9880d681SAndroid Build Coastguard Worker     if (LBO && LBO->getOpcode() == Instruction::Add) {
2625*9880d681SAndroid Build Coastguard Worker       A = LBO->getOperand(0); B = LBO->getOperand(1);
2626*9880d681SAndroid Build Coastguard Worker       NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2627*9880d681SAndroid Build Coastguard Worker         (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2628*9880d681SAndroid Build Coastguard Worker         (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2629*9880d681SAndroid Build Coastguard Worker     }
2630*9880d681SAndroid Build Coastguard Worker     if (RBO && RBO->getOpcode() == Instruction::Add) {
2631*9880d681SAndroid Build Coastguard Worker       C = RBO->getOperand(0); D = RBO->getOperand(1);
2632*9880d681SAndroid Build Coastguard Worker       NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2633*9880d681SAndroid Build Coastguard Worker         (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2634*9880d681SAndroid Build Coastguard Worker         (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2635*9880d681SAndroid Build Coastguard Worker     }
2636*9880d681SAndroid Build Coastguard Worker 
2637*9880d681SAndroid Build Coastguard Worker     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2638*9880d681SAndroid Build Coastguard Worker     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2639*9880d681SAndroid Build Coastguard Worker       if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2640*9880d681SAndroid Build Coastguard Worker                                       Constant::getNullValue(RHS->getType()),
2641*9880d681SAndroid Build Coastguard Worker                                       Q, MaxRecurse-1))
2642*9880d681SAndroid Build Coastguard Worker         return V;
2643*9880d681SAndroid Build Coastguard Worker 
2644*9880d681SAndroid Build Coastguard Worker     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2645*9880d681SAndroid Build Coastguard Worker     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2646*9880d681SAndroid Build Coastguard Worker       if (Value *V = SimplifyICmpInst(Pred,
2647*9880d681SAndroid Build Coastguard Worker                                       Constant::getNullValue(LHS->getType()),
2648*9880d681SAndroid Build Coastguard Worker                                       C == LHS ? D : C, Q, MaxRecurse-1))
2649*9880d681SAndroid Build Coastguard Worker         return V;
2650*9880d681SAndroid Build Coastguard Worker 
2651*9880d681SAndroid Build Coastguard Worker     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2652*9880d681SAndroid Build Coastguard Worker     if (A && C && (A == C || A == D || B == C || B == D) &&
2653*9880d681SAndroid Build Coastguard Worker         NoLHSWrapProblem && NoRHSWrapProblem) {
2654*9880d681SAndroid Build Coastguard Worker       // Determine Y and Z in the form icmp (X+Y), (X+Z).
2655*9880d681SAndroid Build Coastguard Worker       Value *Y, *Z;
2656*9880d681SAndroid Build Coastguard Worker       if (A == C) {
2657*9880d681SAndroid Build Coastguard Worker         // C + B == C + D  ->  B == D
2658*9880d681SAndroid Build Coastguard Worker         Y = B;
2659*9880d681SAndroid Build Coastguard Worker         Z = D;
2660*9880d681SAndroid Build Coastguard Worker       } else if (A == D) {
2661*9880d681SAndroid Build Coastguard Worker         // D + B == C + D  ->  B == C
2662*9880d681SAndroid Build Coastguard Worker         Y = B;
2663*9880d681SAndroid Build Coastguard Worker         Z = C;
2664*9880d681SAndroid Build Coastguard Worker       } else if (B == C) {
2665*9880d681SAndroid Build Coastguard Worker         // A + C == C + D  ->  A == D
2666*9880d681SAndroid Build Coastguard Worker         Y = A;
2667*9880d681SAndroid Build Coastguard Worker         Z = D;
2668*9880d681SAndroid Build Coastguard Worker       } else {
2669*9880d681SAndroid Build Coastguard Worker         assert(B == D);
2670*9880d681SAndroid Build Coastguard Worker         // A + D == C + D  ->  A == C
2671*9880d681SAndroid Build Coastguard Worker         Y = A;
2672*9880d681SAndroid Build Coastguard Worker         Z = C;
2673*9880d681SAndroid Build Coastguard Worker       }
2674*9880d681SAndroid Build Coastguard Worker       if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
2675*9880d681SAndroid Build Coastguard Worker         return V;
2676*9880d681SAndroid Build Coastguard Worker     }
2677*9880d681SAndroid Build Coastguard Worker   }
2678*9880d681SAndroid Build Coastguard Worker 
2679*9880d681SAndroid Build Coastguard Worker   {
2680*9880d681SAndroid Build Coastguard Worker     Value *Y = nullptr;
2681*9880d681SAndroid Build Coastguard Worker     // icmp pred (or X, Y), X
2682*9880d681SAndroid Build Coastguard Worker     if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2683*9880d681SAndroid Build Coastguard Worker       if (Pred == ICmpInst::ICMP_ULT)
2684*9880d681SAndroid Build Coastguard Worker         return getFalse(ITy);
2685*9880d681SAndroid Build Coastguard Worker       if (Pred == ICmpInst::ICMP_UGE)
2686*9880d681SAndroid Build Coastguard Worker         return getTrue(ITy);
2687*9880d681SAndroid Build Coastguard Worker 
2688*9880d681SAndroid Build Coastguard Worker       if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2689*9880d681SAndroid Build Coastguard Worker         bool RHSKnownNonNegative, RHSKnownNegative;
2690*9880d681SAndroid Build Coastguard Worker         bool YKnownNonNegative, YKnownNegative;
2691*9880d681SAndroid Build Coastguard Worker         ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, Q.DL, 0,
2692*9880d681SAndroid Build Coastguard Worker                        Q.AC, Q.CxtI, Q.DT);
2693*9880d681SAndroid Build Coastguard Worker         ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
2694*9880d681SAndroid Build Coastguard Worker                        Q.CxtI, Q.DT);
2695*9880d681SAndroid Build Coastguard Worker         if (RHSKnownNonNegative && YKnownNegative)
2696*9880d681SAndroid Build Coastguard Worker           return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2697*9880d681SAndroid Build Coastguard Worker         if (RHSKnownNegative || YKnownNonNegative)
2698*9880d681SAndroid Build Coastguard Worker           return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2699*9880d681SAndroid Build Coastguard Worker       }
2700*9880d681SAndroid Build Coastguard Worker     }
2701*9880d681SAndroid Build Coastguard Worker     // icmp pred X, (or X, Y)
2702*9880d681SAndroid Build Coastguard Worker     if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2703*9880d681SAndroid Build Coastguard Worker       if (Pred == ICmpInst::ICMP_ULE)
2704*9880d681SAndroid Build Coastguard Worker         return getTrue(ITy);
2705*9880d681SAndroid Build Coastguard Worker       if (Pred == ICmpInst::ICMP_UGT)
2706*9880d681SAndroid Build Coastguard Worker         return getFalse(ITy);
2707*9880d681SAndroid Build Coastguard Worker 
2708*9880d681SAndroid Build Coastguard Worker       if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2709*9880d681SAndroid Build Coastguard Worker         bool LHSKnownNonNegative, LHSKnownNegative;
2710*9880d681SAndroid Build Coastguard Worker         bool YKnownNonNegative, YKnownNegative;
2711*9880d681SAndroid Build Coastguard Worker         ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0,
2712*9880d681SAndroid Build Coastguard Worker                        Q.AC, Q.CxtI, Q.DT);
2713*9880d681SAndroid Build Coastguard Worker         ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
2714*9880d681SAndroid Build Coastguard Worker                        Q.CxtI, Q.DT);
2715*9880d681SAndroid Build Coastguard Worker         if (LHSKnownNonNegative && YKnownNegative)
2716*9880d681SAndroid Build Coastguard Worker           return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2717*9880d681SAndroid Build Coastguard Worker         if (LHSKnownNegative || YKnownNonNegative)
2718*9880d681SAndroid Build Coastguard Worker           return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2719*9880d681SAndroid Build Coastguard Worker       }
2720*9880d681SAndroid Build Coastguard Worker     }
2721*9880d681SAndroid Build Coastguard Worker   }
2722*9880d681SAndroid Build Coastguard Worker 
2723*9880d681SAndroid Build Coastguard Worker   // icmp pred (and X, Y), X
2724*9880d681SAndroid Build Coastguard Worker   if (LBO && match(LBO, m_CombineOr(m_And(m_Value(), m_Specific(RHS)),
2725*9880d681SAndroid Build Coastguard Worker                                     m_And(m_Specific(RHS), m_Value())))) {
2726*9880d681SAndroid Build Coastguard Worker     if (Pred == ICmpInst::ICMP_UGT)
2727*9880d681SAndroid Build Coastguard Worker       return getFalse(ITy);
2728*9880d681SAndroid Build Coastguard Worker     if (Pred == ICmpInst::ICMP_ULE)
2729*9880d681SAndroid Build Coastguard Worker       return getTrue(ITy);
2730*9880d681SAndroid Build Coastguard Worker   }
2731*9880d681SAndroid Build Coastguard Worker   // icmp pred X, (and X, Y)
2732*9880d681SAndroid Build Coastguard Worker   if (RBO && match(RBO, m_CombineOr(m_And(m_Value(), m_Specific(LHS)),
2733*9880d681SAndroid Build Coastguard Worker                                     m_And(m_Specific(LHS), m_Value())))) {
2734*9880d681SAndroid Build Coastguard Worker     if (Pred == ICmpInst::ICMP_UGE)
2735*9880d681SAndroid Build Coastguard Worker       return getTrue(ITy);
2736*9880d681SAndroid Build Coastguard Worker     if (Pred == ICmpInst::ICMP_ULT)
2737*9880d681SAndroid Build Coastguard Worker       return getFalse(ITy);
2738*9880d681SAndroid Build Coastguard Worker   }
2739*9880d681SAndroid Build Coastguard Worker 
2740*9880d681SAndroid Build Coastguard Worker   // 0 - (zext X) pred C
2741*9880d681SAndroid Build Coastguard Worker   if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2742*9880d681SAndroid Build Coastguard Worker     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2743*9880d681SAndroid Build Coastguard Worker       if (RHSC->getValue().isStrictlyPositive()) {
2744*9880d681SAndroid Build Coastguard Worker         if (Pred == ICmpInst::ICMP_SLT)
2745*9880d681SAndroid Build Coastguard Worker           return ConstantInt::getTrue(RHSC->getContext());
2746*9880d681SAndroid Build Coastguard Worker         if (Pred == ICmpInst::ICMP_SGE)
2747*9880d681SAndroid Build Coastguard Worker           return ConstantInt::getFalse(RHSC->getContext());
2748*9880d681SAndroid Build Coastguard Worker         if (Pred == ICmpInst::ICMP_EQ)
2749*9880d681SAndroid Build Coastguard Worker           return ConstantInt::getFalse(RHSC->getContext());
2750*9880d681SAndroid Build Coastguard Worker         if (Pred == ICmpInst::ICMP_NE)
2751*9880d681SAndroid Build Coastguard Worker           return ConstantInt::getTrue(RHSC->getContext());
2752*9880d681SAndroid Build Coastguard Worker       }
2753*9880d681SAndroid Build Coastguard Worker       if (RHSC->getValue().isNonNegative()) {
2754*9880d681SAndroid Build Coastguard Worker         if (Pred == ICmpInst::ICMP_SLE)
2755*9880d681SAndroid Build Coastguard Worker           return ConstantInt::getTrue(RHSC->getContext());
2756*9880d681SAndroid Build Coastguard Worker         if (Pred == ICmpInst::ICMP_SGT)
2757*9880d681SAndroid Build Coastguard Worker           return ConstantInt::getFalse(RHSC->getContext());
2758*9880d681SAndroid Build Coastguard Worker       }
2759*9880d681SAndroid Build Coastguard Worker     }
2760*9880d681SAndroid Build Coastguard Worker   }
2761*9880d681SAndroid Build Coastguard Worker 
2762*9880d681SAndroid Build Coastguard Worker   // icmp pred (urem X, Y), Y
2763*9880d681SAndroid Build Coastguard Worker   if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2764*9880d681SAndroid Build Coastguard Worker     bool KnownNonNegative, KnownNegative;
2765*9880d681SAndroid Build Coastguard Worker     switch (Pred) {
2766*9880d681SAndroid Build Coastguard Worker     default:
2767*9880d681SAndroid Build Coastguard Worker       break;
2768*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SGT:
2769*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SGE:
2770*9880d681SAndroid Build Coastguard Worker       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2771*9880d681SAndroid Build Coastguard Worker                      Q.CxtI, Q.DT);
2772*9880d681SAndroid Build Coastguard Worker       if (!KnownNonNegative)
2773*9880d681SAndroid Build Coastguard Worker         break;
2774*9880d681SAndroid Build Coastguard Worker       // fall-through
2775*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_EQ:
2776*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_UGT:
2777*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_UGE:
2778*9880d681SAndroid Build Coastguard Worker       return getFalse(ITy);
2779*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SLT:
2780*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SLE:
2781*9880d681SAndroid Build Coastguard Worker       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2782*9880d681SAndroid Build Coastguard Worker                      Q.CxtI, Q.DT);
2783*9880d681SAndroid Build Coastguard Worker       if (!KnownNonNegative)
2784*9880d681SAndroid Build Coastguard Worker         break;
2785*9880d681SAndroid Build Coastguard Worker       // fall-through
2786*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_NE:
2787*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_ULT:
2788*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_ULE:
2789*9880d681SAndroid Build Coastguard Worker       return getTrue(ITy);
2790*9880d681SAndroid Build Coastguard Worker     }
2791*9880d681SAndroid Build Coastguard Worker   }
2792*9880d681SAndroid Build Coastguard Worker 
2793*9880d681SAndroid Build Coastguard Worker   // icmp pred X, (urem Y, X)
2794*9880d681SAndroid Build Coastguard Worker   if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2795*9880d681SAndroid Build Coastguard Worker     bool KnownNonNegative, KnownNegative;
2796*9880d681SAndroid Build Coastguard Worker     switch (Pred) {
2797*9880d681SAndroid Build Coastguard Worker     default:
2798*9880d681SAndroid Build Coastguard Worker       break;
2799*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SGT:
2800*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SGE:
2801*9880d681SAndroid Build Coastguard Worker       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2802*9880d681SAndroid Build Coastguard Worker                      Q.CxtI, Q.DT);
2803*9880d681SAndroid Build Coastguard Worker       if (!KnownNonNegative)
2804*9880d681SAndroid Build Coastguard Worker         break;
2805*9880d681SAndroid Build Coastguard Worker       // fall-through
2806*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_NE:
2807*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_UGT:
2808*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_UGE:
2809*9880d681SAndroid Build Coastguard Worker       return getTrue(ITy);
2810*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SLT:
2811*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_SLE:
2812*9880d681SAndroid Build Coastguard Worker       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2813*9880d681SAndroid Build Coastguard Worker                      Q.CxtI, Q.DT);
2814*9880d681SAndroid Build Coastguard Worker       if (!KnownNonNegative)
2815*9880d681SAndroid Build Coastguard Worker         break;
2816*9880d681SAndroid Build Coastguard Worker       // fall-through
2817*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_EQ:
2818*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_ULT:
2819*9880d681SAndroid Build Coastguard Worker     case ICmpInst::ICMP_ULE:
2820*9880d681SAndroid Build Coastguard Worker       return getFalse(ITy);
2821*9880d681SAndroid Build Coastguard Worker     }
2822*9880d681SAndroid Build Coastguard Worker   }
2823*9880d681SAndroid Build Coastguard Worker 
2824*9880d681SAndroid Build Coastguard Worker   // x >> y <=u x
2825*9880d681SAndroid Build Coastguard Worker   // x udiv y <=u x.
2826*9880d681SAndroid Build Coastguard Worker   if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2827*9880d681SAndroid Build Coastguard Worker               match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2828*9880d681SAndroid Build Coastguard Worker     // icmp pred (X op Y), X
2829*9880d681SAndroid Build Coastguard Worker     if (Pred == ICmpInst::ICMP_UGT)
2830*9880d681SAndroid Build Coastguard Worker       return getFalse(ITy);
2831*9880d681SAndroid Build Coastguard Worker     if (Pred == ICmpInst::ICMP_ULE)
2832*9880d681SAndroid Build Coastguard Worker       return getTrue(ITy);
2833*9880d681SAndroid Build Coastguard Worker   }
2834*9880d681SAndroid Build Coastguard Worker 
2835*9880d681SAndroid Build Coastguard Worker   // handle:
2836*9880d681SAndroid Build Coastguard Worker   //   CI2 << X == CI
2837*9880d681SAndroid Build Coastguard Worker   //   CI2 << X != CI
2838*9880d681SAndroid Build Coastguard Worker   //
2839*9880d681SAndroid Build Coastguard Worker   //   where CI2 is a power of 2 and CI isn't
2840*9880d681SAndroid Build Coastguard Worker   if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2841*9880d681SAndroid Build Coastguard Worker     const APInt *CI2Val, *CIVal = &CI->getValue();
2842*9880d681SAndroid Build Coastguard Worker     if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2843*9880d681SAndroid Build Coastguard Worker         CI2Val->isPowerOf2()) {
2844*9880d681SAndroid Build Coastguard Worker       if (!CIVal->isPowerOf2()) {
2845*9880d681SAndroid Build Coastguard Worker         // CI2 << X can equal zero in some circumstances,
2846*9880d681SAndroid Build Coastguard Worker         // this simplification is unsafe if CI is zero.
2847*9880d681SAndroid Build Coastguard Worker         //
2848*9880d681SAndroid Build Coastguard Worker         // We know it is safe if:
2849*9880d681SAndroid Build Coastguard Worker         // - The shift is nsw, we can't shift out the one bit.
2850*9880d681SAndroid Build Coastguard Worker         // - The shift is nuw, we can't shift out the one bit.
2851*9880d681SAndroid Build Coastguard Worker         // - CI2 is one
2852*9880d681SAndroid Build Coastguard Worker         // - CI isn't zero
2853*9880d681SAndroid Build Coastguard Worker         if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2854*9880d681SAndroid Build Coastguard Worker             *CI2Val == 1 || !CI->isZero()) {
2855*9880d681SAndroid Build Coastguard Worker           if (Pred == ICmpInst::ICMP_EQ)
2856*9880d681SAndroid Build Coastguard Worker             return ConstantInt::getFalse(RHS->getContext());
2857*9880d681SAndroid Build Coastguard Worker           if (Pred == ICmpInst::ICMP_NE)
2858*9880d681SAndroid Build Coastguard Worker             return ConstantInt::getTrue(RHS->getContext());
2859*9880d681SAndroid Build Coastguard Worker         }
2860*9880d681SAndroid Build Coastguard Worker       }
2861*9880d681SAndroid Build Coastguard Worker       if (CIVal->isSignBit() && *CI2Val == 1) {
2862*9880d681SAndroid Build Coastguard Worker         if (Pred == ICmpInst::ICMP_UGT)
2863*9880d681SAndroid Build Coastguard Worker           return ConstantInt::getFalse(RHS->getContext());
2864*9880d681SAndroid Build Coastguard Worker         if (Pred == ICmpInst::ICMP_ULE)
2865*9880d681SAndroid Build Coastguard Worker           return ConstantInt::getTrue(RHS->getContext());
2866*9880d681SAndroid Build Coastguard Worker       }
2867*9880d681SAndroid Build Coastguard Worker     }
2868*9880d681SAndroid Build Coastguard Worker   }
2869*9880d681SAndroid Build Coastguard Worker 
2870*9880d681SAndroid Build Coastguard Worker   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2871*9880d681SAndroid Build Coastguard Worker       LBO->getOperand(1) == RBO->getOperand(1)) {
2872*9880d681SAndroid Build Coastguard Worker     switch (LBO->getOpcode()) {
2873*9880d681SAndroid Build Coastguard Worker     default: break;
2874*9880d681SAndroid Build Coastguard Worker     case Instruction::UDiv:
2875*9880d681SAndroid Build Coastguard Worker     case Instruction::LShr:
2876*9880d681SAndroid Build Coastguard Worker       if (ICmpInst::isSigned(Pred))
2877*9880d681SAndroid Build Coastguard Worker         break;
2878*9880d681SAndroid Build Coastguard Worker       // fall-through
2879*9880d681SAndroid Build Coastguard Worker     case Instruction::SDiv:
2880*9880d681SAndroid Build Coastguard Worker     case Instruction::AShr:
2881*9880d681SAndroid Build Coastguard Worker       if (!LBO->isExact() || !RBO->isExact())
2882*9880d681SAndroid Build Coastguard Worker         break;
2883*9880d681SAndroid Build Coastguard Worker       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2884*9880d681SAndroid Build Coastguard Worker                                       RBO->getOperand(0), Q, MaxRecurse-1))
2885*9880d681SAndroid Build Coastguard Worker         return V;
2886*9880d681SAndroid Build Coastguard Worker       break;
2887*9880d681SAndroid Build Coastguard Worker     case Instruction::Shl: {
2888*9880d681SAndroid Build Coastguard Worker       bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2889*9880d681SAndroid Build Coastguard Worker       bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2890*9880d681SAndroid Build Coastguard Worker       if (!NUW && !NSW)
2891*9880d681SAndroid Build Coastguard Worker         break;
2892*9880d681SAndroid Build Coastguard Worker       if (!NSW && ICmpInst::isSigned(Pred))
2893*9880d681SAndroid Build Coastguard Worker         break;
2894*9880d681SAndroid Build Coastguard Worker       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2895*9880d681SAndroid Build Coastguard Worker                                       RBO->getOperand(0), Q, MaxRecurse-1))
2896*9880d681SAndroid Build Coastguard Worker         return V;
2897*9880d681SAndroid Build Coastguard Worker       break;
2898*9880d681SAndroid Build Coastguard Worker     }
2899*9880d681SAndroid Build Coastguard Worker     }
2900*9880d681SAndroid Build Coastguard Worker   }
2901*9880d681SAndroid Build Coastguard Worker 
2902*9880d681SAndroid Build Coastguard Worker   // Simplify comparisons involving max/min.
2903*9880d681SAndroid Build Coastguard Worker   Value *A, *B;
2904*9880d681SAndroid Build Coastguard Worker   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2905*9880d681SAndroid Build Coastguard Worker   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2906*9880d681SAndroid Build Coastguard Worker 
2907*9880d681SAndroid Build Coastguard Worker   // Signed variants on "max(a,b)>=a -> true".
2908*9880d681SAndroid Build Coastguard Worker   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2909*9880d681SAndroid Build Coastguard Worker     if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2910*9880d681SAndroid Build Coastguard Worker     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2911*9880d681SAndroid Build Coastguard Worker     // We analyze this as smax(A, B) pred A.
2912*9880d681SAndroid Build Coastguard Worker     P = Pred;
2913*9880d681SAndroid Build Coastguard Worker   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2914*9880d681SAndroid Build Coastguard Worker              (A == LHS || B == LHS)) {
2915*9880d681SAndroid Build Coastguard Worker     if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2916*9880d681SAndroid Build Coastguard Worker     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2917*9880d681SAndroid Build Coastguard Worker     // We analyze this as smax(A, B) swapped-pred A.
2918*9880d681SAndroid Build Coastguard Worker     P = CmpInst::getSwappedPredicate(Pred);
2919*9880d681SAndroid Build Coastguard Worker   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2920*9880d681SAndroid Build Coastguard Worker              (A == RHS || B == RHS)) {
2921*9880d681SAndroid Build Coastguard Worker     if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2922*9880d681SAndroid Build Coastguard Worker     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2923*9880d681SAndroid Build Coastguard Worker     // We analyze this as smax(-A, -B) swapped-pred -A.
2924*9880d681SAndroid Build Coastguard Worker     // Note that we do not need to actually form -A or -B thanks to EqP.
2925*9880d681SAndroid Build Coastguard Worker     P = CmpInst::getSwappedPredicate(Pred);
2926*9880d681SAndroid Build Coastguard Worker   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2927*9880d681SAndroid Build Coastguard Worker              (A == LHS || B == LHS)) {
2928*9880d681SAndroid Build Coastguard Worker     if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2929*9880d681SAndroid Build Coastguard Worker     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2930*9880d681SAndroid Build Coastguard Worker     // We analyze this as smax(-A, -B) pred -A.
2931*9880d681SAndroid Build Coastguard Worker     // Note that we do not need to actually form -A or -B thanks to EqP.
2932*9880d681SAndroid Build Coastguard Worker     P = Pred;
2933*9880d681SAndroid Build Coastguard Worker   }
2934*9880d681SAndroid Build Coastguard Worker   if (P != CmpInst::BAD_ICMP_PREDICATE) {
2935*9880d681SAndroid Build Coastguard Worker     // Cases correspond to "max(A, B) p A".
2936*9880d681SAndroid Build Coastguard Worker     switch (P) {
2937*9880d681SAndroid Build Coastguard Worker     default:
2938*9880d681SAndroid Build Coastguard Worker       break;
2939*9880d681SAndroid Build Coastguard Worker     case CmpInst::ICMP_EQ:
2940*9880d681SAndroid Build Coastguard Worker     case CmpInst::ICMP_SLE:
2941*9880d681SAndroid Build Coastguard Worker       // Equivalent to "A EqP B".  This may be the same as the condition tested
2942*9880d681SAndroid Build Coastguard Worker       // in the max/min; if so, we can just return that.
2943*9880d681SAndroid Build Coastguard Worker       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2944*9880d681SAndroid Build Coastguard Worker         return V;
2945*9880d681SAndroid Build Coastguard Worker       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2946*9880d681SAndroid Build Coastguard Worker         return V;
2947*9880d681SAndroid Build Coastguard Worker       // Otherwise, see if "A EqP B" simplifies.
2948*9880d681SAndroid Build Coastguard Worker       if (MaxRecurse)
2949*9880d681SAndroid Build Coastguard Worker         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2950*9880d681SAndroid Build Coastguard Worker           return V;
2951*9880d681SAndroid Build Coastguard Worker       break;
2952*9880d681SAndroid Build Coastguard Worker     case CmpInst::ICMP_NE:
2953*9880d681SAndroid Build Coastguard Worker     case CmpInst::ICMP_SGT: {
2954*9880d681SAndroid Build Coastguard Worker       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2955*9880d681SAndroid Build Coastguard Worker       // Equivalent to "A InvEqP B".  This may be the same as the condition
2956*9880d681SAndroid Build Coastguard Worker       // tested in the max/min; if so, we can just return that.
2957*9880d681SAndroid Build Coastguard Worker       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2958*9880d681SAndroid Build Coastguard Worker         return V;
2959*9880d681SAndroid Build Coastguard Worker       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2960*9880d681SAndroid Build Coastguard Worker         return V;
2961*9880d681SAndroid Build Coastguard Worker       // Otherwise, see if "A InvEqP B" simplifies.
2962*9880d681SAndroid Build Coastguard Worker       if (MaxRecurse)
2963*9880d681SAndroid Build Coastguard Worker         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2964*9880d681SAndroid Build Coastguard Worker           return V;
2965*9880d681SAndroid Build Coastguard Worker       break;
2966*9880d681SAndroid Build Coastguard Worker     }
2967*9880d681SAndroid Build Coastguard Worker     case CmpInst::ICMP_SGE:
2968*9880d681SAndroid Build Coastguard Worker       // Always true.
2969*9880d681SAndroid Build Coastguard Worker       return getTrue(ITy);
2970*9880d681SAndroid Build Coastguard Worker     case CmpInst::ICMP_SLT:
2971*9880d681SAndroid Build Coastguard Worker       // Always false.
2972*9880d681SAndroid Build Coastguard Worker       return getFalse(ITy);
2973*9880d681SAndroid Build Coastguard Worker     }
2974*9880d681SAndroid Build Coastguard Worker   }
2975*9880d681SAndroid Build Coastguard Worker 
2976*9880d681SAndroid Build Coastguard Worker   // Unsigned variants on "max(a,b)>=a -> true".
2977*9880d681SAndroid Build Coastguard Worker   P = CmpInst::BAD_ICMP_PREDICATE;
2978*9880d681SAndroid Build Coastguard Worker   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2979*9880d681SAndroid Build Coastguard Worker     if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2980*9880d681SAndroid Build Coastguard Worker     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2981*9880d681SAndroid Build Coastguard Worker     // We analyze this as umax(A, B) pred A.
2982*9880d681SAndroid Build Coastguard Worker     P = Pred;
2983*9880d681SAndroid Build Coastguard Worker   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2984*9880d681SAndroid Build Coastguard Worker              (A == LHS || B == LHS)) {
2985*9880d681SAndroid Build Coastguard Worker     if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2986*9880d681SAndroid Build Coastguard Worker     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2987*9880d681SAndroid Build Coastguard Worker     // We analyze this as umax(A, B) swapped-pred A.
2988*9880d681SAndroid Build Coastguard Worker     P = CmpInst::getSwappedPredicate(Pred);
2989*9880d681SAndroid Build Coastguard Worker   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2990*9880d681SAndroid Build Coastguard Worker              (A == RHS || B == RHS)) {
2991*9880d681SAndroid Build Coastguard Worker     if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2992*9880d681SAndroid Build Coastguard Worker     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2993*9880d681SAndroid Build Coastguard Worker     // We analyze this as umax(-A, -B) swapped-pred -A.
2994*9880d681SAndroid Build Coastguard Worker     // Note that we do not need to actually form -A or -B thanks to EqP.
2995*9880d681SAndroid Build Coastguard Worker     P = CmpInst::getSwappedPredicate(Pred);
2996*9880d681SAndroid Build Coastguard Worker   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2997*9880d681SAndroid Build Coastguard Worker              (A == LHS || B == LHS)) {
2998*9880d681SAndroid Build Coastguard Worker     if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2999*9880d681SAndroid Build Coastguard Worker     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3000*9880d681SAndroid Build Coastguard Worker     // We analyze this as umax(-A, -B) pred -A.
3001*9880d681SAndroid Build Coastguard Worker     // Note that we do not need to actually form -A or -B thanks to EqP.
3002*9880d681SAndroid Build Coastguard Worker     P = Pred;
3003*9880d681SAndroid Build Coastguard Worker   }
3004*9880d681SAndroid Build Coastguard Worker   if (P != CmpInst::BAD_ICMP_PREDICATE) {
3005*9880d681SAndroid Build Coastguard Worker     // Cases correspond to "max(A, B) p A".
3006*9880d681SAndroid Build Coastguard Worker     switch (P) {
3007*9880d681SAndroid Build Coastguard Worker     default:
3008*9880d681SAndroid Build Coastguard Worker       break;
3009*9880d681SAndroid Build Coastguard Worker     case CmpInst::ICMP_EQ:
3010*9880d681SAndroid Build Coastguard Worker     case CmpInst::ICMP_ULE:
3011*9880d681SAndroid Build Coastguard Worker       // Equivalent to "A EqP B".  This may be the same as the condition tested
3012*9880d681SAndroid Build Coastguard Worker       // in the max/min; if so, we can just return that.
3013*9880d681SAndroid Build Coastguard Worker       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3014*9880d681SAndroid Build Coastguard Worker         return V;
3015*9880d681SAndroid Build Coastguard Worker       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3016*9880d681SAndroid Build Coastguard Worker         return V;
3017*9880d681SAndroid Build Coastguard Worker       // Otherwise, see if "A EqP B" simplifies.
3018*9880d681SAndroid Build Coastguard Worker       if (MaxRecurse)
3019*9880d681SAndroid Build Coastguard Worker         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
3020*9880d681SAndroid Build Coastguard Worker           return V;
3021*9880d681SAndroid Build Coastguard Worker       break;
3022*9880d681SAndroid Build Coastguard Worker     case CmpInst::ICMP_NE:
3023*9880d681SAndroid Build Coastguard Worker     case CmpInst::ICMP_UGT: {
3024*9880d681SAndroid Build Coastguard Worker       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3025*9880d681SAndroid Build Coastguard Worker       // Equivalent to "A InvEqP B".  This may be the same as the condition
3026*9880d681SAndroid Build Coastguard Worker       // tested in the max/min; if so, we can just return that.
3027*9880d681SAndroid Build Coastguard Worker       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3028*9880d681SAndroid Build Coastguard Worker         return V;
3029*9880d681SAndroid Build Coastguard Worker       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3030*9880d681SAndroid Build Coastguard Worker         return V;
3031*9880d681SAndroid Build Coastguard Worker       // Otherwise, see if "A InvEqP B" simplifies.
3032*9880d681SAndroid Build Coastguard Worker       if (MaxRecurse)
3033*9880d681SAndroid Build Coastguard Worker         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
3034*9880d681SAndroid Build Coastguard Worker           return V;
3035*9880d681SAndroid Build Coastguard Worker       break;
3036*9880d681SAndroid Build Coastguard Worker     }
3037*9880d681SAndroid Build Coastguard Worker     case CmpInst::ICMP_UGE:
3038*9880d681SAndroid Build Coastguard Worker       // Always true.
3039*9880d681SAndroid Build Coastguard Worker       return getTrue(ITy);
3040*9880d681SAndroid Build Coastguard Worker     case CmpInst::ICMP_ULT:
3041*9880d681SAndroid Build Coastguard Worker       // Always false.
3042*9880d681SAndroid Build Coastguard Worker       return getFalse(ITy);
3043*9880d681SAndroid Build Coastguard Worker     }
3044*9880d681SAndroid Build Coastguard Worker   }
3045*9880d681SAndroid Build Coastguard Worker 
3046*9880d681SAndroid Build Coastguard Worker   // Variants on "max(x,y) >= min(x,z)".
3047*9880d681SAndroid Build Coastguard Worker   Value *C, *D;
3048*9880d681SAndroid Build Coastguard Worker   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3049*9880d681SAndroid Build Coastguard Worker       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3050*9880d681SAndroid Build Coastguard Worker       (A == C || A == D || B == C || B == D)) {
3051*9880d681SAndroid Build Coastguard Worker     // max(x, ?) pred min(x, ?).
3052*9880d681SAndroid Build Coastguard Worker     if (Pred == CmpInst::ICMP_SGE)
3053*9880d681SAndroid Build Coastguard Worker       // Always true.
3054*9880d681SAndroid Build Coastguard Worker       return getTrue(ITy);
3055*9880d681SAndroid Build Coastguard Worker     if (Pred == CmpInst::ICMP_SLT)
3056*9880d681SAndroid Build Coastguard Worker       // Always false.
3057*9880d681SAndroid Build Coastguard Worker       return getFalse(ITy);
3058*9880d681SAndroid Build Coastguard Worker   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3059*9880d681SAndroid Build Coastguard Worker              match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3060*9880d681SAndroid Build Coastguard Worker              (A == C || A == D || B == C || B == D)) {
3061*9880d681SAndroid Build Coastguard Worker     // min(x, ?) pred max(x, ?).
3062*9880d681SAndroid Build Coastguard Worker     if (Pred == CmpInst::ICMP_SLE)
3063*9880d681SAndroid Build Coastguard Worker       // Always true.
3064*9880d681SAndroid Build Coastguard Worker       return getTrue(ITy);
3065*9880d681SAndroid Build Coastguard Worker     if (Pred == CmpInst::ICMP_SGT)
3066*9880d681SAndroid Build Coastguard Worker       // Always false.
3067*9880d681SAndroid Build Coastguard Worker       return getFalse(ITy);
3068*9880d681SAndroid Build Coastguard Worker   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3069*9880d681SAndroid Build Coastguard Worker              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3070*9880d681SAndroid Build Coastguard Worker              (A == C || A == D || B == C || B == D)) {
3071*9880d681SAndroid Build Coastguard Worker     // max(x, ?) pred min(x, ?).
3072*9880d681SAndroid Build Coastguard Worker     if (Pred == CmpInst::ICMP_UGE)
3073*9880d681SAndroid Build Coastguard Worker       // Always true.
3074*9880d681SAndroid Build Coastguard Worker       return getTrue(ITy);
3075*9880d681SAndroid Build Coastguard Worker     if (Pred == CmpInst::ICMP_ULT)
3076*9880d681SAndroid Build Coastguard Worker       // Always false.
3077*9880d681SAndroid Build Coastguard Worker       return getFalse(ITy);
3078*9880d681SAndroid Build Coastguard Worker   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3079*9880d681SAndroid Build Coastguard Worker              match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3080*9880d681SAndroid Build Coastguard Worker              (A == C || A == D || B == C || B == D)) {
3081*9880d681SAndroid Build Coastguard Worker     // min(x, ?) pred max(x, ?).
3082*9880d681SAndroid Build Coastguard Worker     if (Pred == CmpInst::ICMP_ULE)
3083*9880d681SAndroid Build Coastguard Worker       // Always true.
3084*9880d681SAndroid Build Coastguard Worker       return getTrue(ITy);
3085*9880d681SAndroid Build Coastguard Worker     if (Pred == CmpInst::ICMP_UGT)
3086*9880d681SAndroid Build Coastguard Worker       // Always false.
3087*9880d681SAndroid Build Coastguard Worker       return getFalse(ITy);
3088*9880d681SAndroid Build Coastguard Worker   }
3089*9880d681SAndroid Build Coastguard Worker 
3090*9880d681SAndroid Build Coastguard Worker   // Simplify comparisons of related pointers using a powerful, recursive
3091*9880d681SAndroid Build Coastguard Worker   // GEP-walk when we have target data available..
3092*9880d681SAndroid Build Coastguard Worker   if (LHS->getType()->isPointerTy())
3093*9880d681SAndroid Build Coastguard Worker     if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI, LHS, RHS))
3094*9880d681SAndroid Build Coastguard Worker       return C;
3095*9880d681SAndroid Build Coastguard Worker 
3096*9880d681SAndroid Build Coastguard Worker   if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3097*9880d681SAndroid Build Coastguard Worker     if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3098*9880d681SAndroid Build Coastguard Worker       if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3099*9880d681SAndroid Build Coastguard Worker           GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3100*9880d681SAndroid Build Coastguard Worker           (ICmpInst::isEquality(Pred) ||
3101*9880d681SAndroid Build Coastguard Worker            (GLHS->isInBounds() && GRHS->isInBounds() &&
3102*9880d681SAndroid Build Coastguard Worker             Pred == ICmpInst::getSignedPredicate(Pred)))) {
3103*9880d681SAndroid Build Coastguard Worker         // The bases are equal and the indices are constant.  Build a constant
3104*9880d681SAndroid Build Coastguard Worker         // expression GEP with the same indices and a null base pointer to see
3105*9880d681SAndroid Build Coastguard Worker         // what constant folding can make out of it.
3106*9880d681SAndroid Build Coastguard Worker         Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3107*9880d681SAndroid Build Coastguard Worker         SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
3108*9880d681SAndroid Build Coastguard Worker         Constant *NewLHS = ConstantExpr::getGetElementPtr(
3109*9880d681SAndroid Build Coastguard Worker             GLHS->getSourceElementType(), Null, IndicesLHS);
3110*9880d681SAndroid Build Coastguard Worker 
3111*9880d681SAndroid Build Coastguard Worker         SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
3112*9880d681SAndroid Build Coastguard Worker         Constant *NewRHS = ConstantExpr::getGetElementPtr(
3113*9880d681SAndroid Build Coastguard Worker             GLHS->getSourceElementType(), Null, IndicesRHS);
3114*9880d681SAndroid Build Coastguard Worker         return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3115*9880d681SAndroid Build Coastguard Worker       }
3116*9880d681SAndroid Build Coastguard Worker     }
3117*9880d681SAndroid Build Coastguard Worker   }
3118*9880d681SAndroid Build Coastguard Worker 
3119*9880d681SAndroid Build Coastguard Worker   // If a bit is known to be zero for A and known to be one for B,
3120*9880d681SAndroid Build Coastguard Worker   // then A and B cannot be equal.
3121*9880d681SAndroid Build Coastguard Worker   if (ICmpInst::isEquality(Pred)) {
3122*9880d681SAndroid Build Coastguard Worker     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3123*9880d681SAndroid Build Coastguard Worker       uint32_t BitWidth = CI->getBitWidth();
3124*9880d681SAndroid Build Coastguard Worker       APInt LHSKnownZero(BitWidth, 0);
3125*9880d681SAndroid Build Coastguard Worker       APInt LHSKnownOne(BitWidth, 0);
3126*9880d681SAndroid Build Coastguard Worker       computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL, /*Depth=*/0, Q.AC,
3127*9880d681SAndroid Build Coastguard Worker                        Q.CxtI, Q.DT);
3128*9880d681SAndroid Build Coastguard Worker       const APInt &RHSVal = CI->getValue();
3129*9880d681SAndroid Build Coastguard Worker       if (((LHSKnownZero & RHSVal) != 0) || ((LHSKnownOne & ~RHSVal) != 0))
3130*9880d681SAndroid Build Coastguard Worker         return Pred == ICmpInst::ICMP_EQ
3131*9880d681SAndroid Build Coastguard Worker                    ? ConstantInt::getFalse(CI->getContext())
3132*9880d681SAndroid Build Coastguard Worker                    : ConstantInt::getTrue(CI->getContext());
3133*9880d681SAndroid Build Coastguard Worker     }
3134*9880d681SAndroid Build Coastguard Worker   }
3135*9880d681SAndroid Build Coastguard Worker 
3136*9880d681SAndroid Build Coastguard Worker   // If the comparison is with the result of a select instruction, check whether
3137*9880d681SAndroid Build Coastguard Worker   // comparing with either branch of the select always yields the same value.
3138*9880d681SAndroid Build Coastguard Worker   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3139*9880d681SAndroid Build Coastguard Worker     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3140*9880d681SAndroid Build Coastguard Worker       return V;
3141*9880d681SAndroid Build Coastguard Worker 
3142*9880d681SAndroid Build Coastguard Worker   // If the comparison is with the result of a phi instruction, check whether
3143*9880d681SAndroid Build Coastguard Worker   // doing the compare with each incoming phi value yields a common result.
3144*9880d681SAndroid Build Coastguard Worker   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3145*9880d681SAndroid Build Coastguard Worker     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3146*9880d681SAndroid Build Coastguard Worker       return V;
3147*9880d681SAndroid Build Coastguard Worker 
3148*9880d681SAndroid Build Coastguard Worker   return nullptr;
3149*9880d681SAndroid Build Coastguard Worker }
3150*9880d681SAndroid Build Coastguard Worker 
SimplifyICmpInst(unsigned Predicate,Value * LHS,Value * RHS,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)3151*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3152*9880d681SAndroid Build Coastguard Worker                               const DataLayout &DL,
3153*9880d681SAndroid Build Coastguard Worker                               const TargetLibraryInfo *TLI,
3154*9880d681SAndroid Build Coastguard Worker                               const DominatorTree *DT, AssumptionCache *AC,
3155*9880d681SAndroid Build Coastguard Worker                               const Instruction *CxtI) {
3156*9880d681SAndroid Build Coastguard Worker   return ::SimplifyICmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
3157*9880d681SAndroid Build Coastguard Worker                             RecursionLimit);
3158*9880d681SAndroid Build Coastguard Worker }
3159*9880d681SAndroid Build Coastguard Worker 
3160*9880d681SAndroid Build Coastguard Worker /// Given operands for an FCmpInst, see if we can fold the result.
3161*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifyFCmpInst(unsigned Predicate,Value * LHS,Value * RHS,FastMathFlags FMF,const Query & Q,unsigned MaxRecurse)3162*9880d681SAndroid Build Coastguard Worker static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3163*9880d681SAndroid Build Coastguard Worker                                FastMathFlags FMF, const Query &Q,
3164*9880d681SAndroid Build Coastguard Worker                                unsigned MaxRecurse) {
3165*9880d681SAndroid Build Coastguard Worker   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3166*9880d681SAndroid Build Coastguard Worker   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3167*9880d681SAndroid Build Coastguard Worker 
3168*9880d681SAndroid Build Coastguard Worker   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3169*9880d681SAndroid Build Coastguard Worker     if (Constant *CRHS = dyn_cast<Constant>(RHS))
3170*9880d681SAndroid Build Coastguard Worker       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3171*9880d681SAndroid Build Coastguard Worker 
3172*9880d681SAndroid Build Coastguard Worker     // If we have a constant, make sure it is on the RHS.
3173*9880d681SAndroid Build Coastguard Worker     std::swap(LHS, RHS);
3174*9880d681SAndroid Build Coastguard Worker     Pred = CmpInst::getSwappedPredicate(Pred);
3175*9880d681SAndroid Build Coastguard Worker   }
3176*9880d681SAndroid Build Coastguard Worker 
3177*9880d681SAndroid Build Coastguard Worker   // Fold trivial predicates.
3178*9880d681SAndroid Build Coastguard Worker   if (Pred == FCmpInst::FCMP_FALSE)
3179*9880d681SAndroid Build Coastguard Worker     return ConstantInt::get(GetCompareTy(LHS), 0);
3180*9880d681SAndroid Build Coastguard Worker   if (Pred == FCmpInst::FCMP_TRUE)
3181*9880d681SAndroid Build Coastguard Worker     return ConstantInt::get(GetCompareTy(LHS), 1);
3182*9880d681SAndroid Build Coastguard Worker 
3183*9880d681SAndroid Build Coastguard Worker   // UNO/ORD predicates can be trivially folded if NaNs are ignored.
3184*9880d681SAndroid Build Coastguard Worker   if (FMF.noNaNs()) {
3185*9880d681SAndroid Build Coastguard Worker     if (Pred == FCmpInst::FCMP_UNO)
3186*9880d681SAndroid Build Coastguard Worker       return ConstantInt::get(GetCompareTy(LHS), 0);
3187*9880d681SAndroid Build Coastguard Worker     if (Pred == FCmpInst::FCMP_ORD)
3188*9880d681SAndroid Build Coastguard Worker       return ConstantInt::get(GetCompareTy(LHS), 1);
3189*9880d681SAndroid Build Coastguard Worker   }
3190*9880d681SAndroid Build Coastguard Worker 
3191*9880d681SAndroid Build Coastguard Worker   // fcmp pred x, undef  and  fcmp pred undef, x
3192*9880d681SAndroid Build Coastguard Worker   // fold to true if unordered, false if ordered
3193*9880d681SAndroid Build Coastguard Worker   if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3194*9880d681SAndroid Build Coastguard Worker     // Choosing NaN for the undef will always make unordered comparison succeed
3195*9880d681SAndroid Build Coastguard Worker     // and ordered comparison fail.
3196*9880d681SAndroid Build Coastguard Worker     return ConstantInt::get(GetCompareTy(LHS), CmpInst::isUnordered(Pred));
3197*9880d681SAndroid Build Coastguard Worker   }
3198*9880d681SAndroid Build Coastguard Worker 
3199*9880d681SAndroid Build Coastguard Worker   // fcmp x,x -> true/false.  Not all compares are foldable.
3200*9880d681SAndroid Build Coastguard Worker   if (LHS == RHS) {
3201*9880d681SAndroid Build Coastguard Worker     if (CmpInst::isTrueWhenEqual(Pred))
3202*9880d681SAndroid Build Coastguard Worker       return ConstantInt::get(GetCompareTy(LHS), 1);
3203*9880d681SAndroid Build Coastguard Worker     if (CmpInst::isFalseWhenEqual(Pred))
3204*9880d681SAndroid Build Coastguard Worker       return ConstantInt::get(GetCompareTy(LHS), 0);
3205*9880d681SAndroid Build Coastguard Worker   }
3206*9880d681SAndroid Build Coastguard Worker 
3207*9880d681SAndroid Build Coastguard Worker   // Handle fcmp with constant RHS
3208*9880d681SAndroid Build Coastguard Worker   const ConstantFP *CFP = nullptr;
3209*9880d681SAndroid Build Coastguard Worker   if (const auto *RHSC = dyn_cast<Constant>(RHS)) {
3210*9880d681SAndroid Build Coastguard Worker     if (RHS->getType()->isVectorTy())
3211*9880d681SAndroid Build Coastguard Worker       CFP = dyn_cast_or_null<ConstantFP>(RHSC->getSplatValue());
3212*9880d681SAndroid Build Coastguard Worker     else
3213*9880d681SAndroid Build Coastguard Worker       CFP = dyn_cast<ConstantFP>(RHSC);
3214*9880d681SAndroid Build Coastguard Worker   }
3215*9880d681SAndroid Build Coastguard Worker   if (CFP) {
3216*9880d681SAndroid Build Coastguard Worker     // If the constant is a nan, see if we can fold the comparison based on it.
3217*9880d681SAndroid Build Coastguard Worker     if (CFP->getValueAPF().isNaN()) {
3218*9880d681SAndroid Build Coastguard Worker       if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
3219*9880d681SAndroid Build Coastguard Worker         return ConstantInt::getFalse(CFP->getContext());
3220*9880d681SAndroid Build Coastguard Worker       assert(FCmpInst::isUnordered(Pred) &&
3221*9880d681SAndroid Build Coastguard Worker              "Comparison must be either ordered or unordered!");
3222*9880d681SAndroid Build Coastguard Worker       // True if unordered.
3223*9880d681SAndroid Build Coastguard Worker       return ConstantInt::get(GetCompareTy(LHS), 1);
3224*9880d681SAndroid Build Coastguard Worker     }
3225*9880d681SAndroid Build Coastguard Worker     // Check whether the constant is an infinity.
3226*9880d681SAndroid Build Coastguard Worker     if (CFP->getValueAPF().isInfinity()) {
3227*9880d681SAndroid Build Coastguard Worker       if (CFP->getValueAPF().isNegative()) {
3228*9880d681SAndroid Build Coastguard Worker         switch (Pred) {
3229*9880d681SAndroid Build Coastguard Worker         case FCmpInst::FCMP_OLT:
3230*9880d681SAndroid Build Coastguard Worker           // No value is ordered and less than negative infinity.
3231*9880d681SAndroid Build Coastguard Worker           return ConstantInt::get(GetCompareTy(LHS), 0);
3232*9880d681SAndroid Build Coastguard Worker         case FCmpInst::FCMP_UGE:
3233*9880d681SAndroid Build Coastguard Worker           // All values are unordered with or at least negative infinity.
3234*9880d681SAndroid Build Coastguard Worker           return ConstantInt::get(GetCompareTy(LHS), 1);
3235*9880d681SAndroid Build Coastguard Worker         default:
3236*9880d681SAndroid Build Coastguard Worker           break;
3237*9880d681SAndroid Build Coastguard Worker         }
3238*9880d681SAndroid Build Coastguard Worker       } else {
3239*9880d681SAndroid Build Coastguard Worker         switch (Pred) {
3240*9880d681SAndroid Build Coastguard Worker         case FCmpInst::FCMP_OGT:
3241*9880d681SAndroid Build Coastguard Worker           // No value is ordered and greater than infinity.
3242*9880d681SAndroid Build Coastguard Worker           return ConstantInt::get(GetCompareTy(LHS), 0);
3243*9880d681SAndroid Build Coastguard Worker         case FCmpInst::FCMP_ULE:
3244*9880d681SAndroid Build Coastguard Worker           // All values are unordered with and at most infinity.
3245*9880d681SAndroid Build Coastguard Worker           return ConstantInt::get(GetCompareTy(LHS), 1);
3246*9880d681SAndroid Build Coastguard Worker         default:
3247*9880d681SAndroid Build Coastguard Worker           break;
3248*9880d681SAndroid Build Coastguard Worker         }
3249*9880d681SAndroid Build Coastguard Worker       }
3250*9880d681SAndroid Build Coastguard Worker     }
3251*9880d681SAndroid Build Coastguard Worker     if (CFP->getValueAPF().isZero()) {
3252*9880d681SAndroid Build Coastguard Worker       switch (Pred) {
3253*9880d681SAndroid Build Coastguard Worker       case FCmpInst::FCMP_UGE:
3254*9880d681SAndroid Build Coastguard Worker         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3255*9880d681SAndroid Build Coastguard Worker           return ConstantInt::get(GetCompareTy(LHS), 1);
3256*9880d681SAndroid Build Coastguard Worker         break;
3257*9880d681SAndroid Build Coastguard Worker       case FCmpInst::FCMP_OLT:
3258*9880d681SAndroid Build Coastguard Worker         // X < 0
3259*9880d681SAndroid Build Coastguard Worker         if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3260*9880d681SAndroid Build Coastguard Worker           return ConstantInt::get(GetCompareTy(LHS), 0);
3261*9880d681SAndroid Build Coastguard Worker         break;
3262*9880d681SAndroid Build Coastguard Worker       default:
3263*9880d681SAndroid Build Coastguard Worker         break;
3264*9880d681SAndroid Build Coastguard Worker       }
3265*9880d681SAndroid Build Coastguard Worker     }
3266*9880d681SAndroid Build Coastguard Worker   }
3267*9880d681SAndroid Build Coastguard Worker 
3268*9880d681SAndroid Build Coastguard Worker   // If the comparison is with the result of a select instruction, check whether
3269*9880d681SAndroid Build Coastguard Worker   // comparing with either branch of the select always yields the same value.
3270*9880d681SAndroid Build Coastguard Worker   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3271*9880d681SAndroid Build Coastguard Worker     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3272*9880d681SAndroid Build Coastguard Worker       return V;
3273*9880d681SAndroid Build Coastguard Worker 
3274*9880d681SAndroid Build Coastguard Worker   // If the comparison is with the result of a phi instruction, check whether
3275*9880d681SAndroid Build Coastguard Worker   // doing the compare with each incoming phi value yields a common result.
3276*9880d681SAndroid Build Coastguard Worker   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3277*9880d681SAndroid Build Coastguard Worker     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3278*9880d681SAndroid Build Coastguard Worker       return V;
3279*9880d681SAndroid Build Coastguard Worker 
3280*9880d681SAndroid Build Coastguard Worker   return nullptr;
3281*9880d681SAndroid Build Coastguard Worker }
3282*9880d681SAndroid Build Coastguard Worker 
SimplifyFCmpInst(unsigned Predicate,Value * LHS,Value * RHS,FastMathFlags FMF,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)3283*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3284*9880d681SAndroid Build Coastguard Worker                               FastMathFlags FMF, const DataLayout &DL,
3285*9880d681SAndroid Build Coastguard Worker                               const TargetLibraryInfo *TLI,
3286*9880d681SAndroid Build Coastguard Worker                               const DominatorTree *DT, AssumptionCache *AC,
3287*9880d681SAndroid Build Coastguard Worker                               const Instruction *CxtI) {
3288*9880d681SAndroid Build Coastguard Worker   return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF,
3289*9880d681SAndroid Build Coastguard Worker                             Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
3290*9880d681SAndroid Build Coastguard Worker }
3291*9880d681SAndroid Build Coastguard Worker 
3292*9880d681SAndroid Build Coastguard Worker /// See if V simplifies when its operand Op is replaced with RepOp.
SimplifyWithOpReplaced(Value * V,Value * Op,Value * RepOp,const Query & Q,unsigned MaxRecurse)3293*9880d681SAndroid Build Coastguard Worker static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3294*9880d681SAndroid Build Coastguard Worker                                            const Query &Q,
3295*9880d681SAndroid Build Coastguard Worker                                            unsigned MaxRecurse) {
3296*9880d681SAndroid Build Coastguard Worker   // Trivial replacement.
3297*9880d681SAndroid Build Coastguard Worker   if (V == Op)
3298*9880d681SAndroid Build Coastguard Worker     return RepOp;
3299*9880d681SAndroid Build Coastguard Worker 
3300*9880d681SAndroid Build Coastguard Worker   auto *I = dyn_cast<Instruction>(V);
3301*9880d681SAndroid Build Coastguard Worker   if (!I)
3302*9880d681SAndroid Build Coastguard Worker     return nullptr;
3303*9880d681SAndroid Build Coastguard Worker 
3304*9880d681SAndroid Build Coastguard Worker   // If this is a binary operator, try to simplify it with the replaced op.
3305*9880d681SAndroid Build Coastguard Worker   if (auto *B = dyn_cast<BinaryOperator>(I)) {
3306*9880d681SAndroid Build Coastguard Worker     // Consider:
3307*9880d681SAndroid Build Coastguard Worker     //   %cmp = icmp eq i32 %x, 2147483647
3308*9880d681SAndroid Build Coastguard Worker     //   %add = add nsw i32 %x, 1
3309*9880d681SAndroid Build Coastguard Worker     //   %sel = select i1 %cmp, i32 -2147483648, i32 %add
3310*9880d681SAndroid Build Coastguard Worker     //
3311*9880d681SAndroid Build Coastguard Worker     // We can't replace %sel with %add unless we strip away the flags.
3312*9880d681SAndroid Build Coastguard Worker     if (isa<OverflowingBinaryOperator>(B))
3313*9880d681SAndroid Build Coastguard Worker       if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
3314*9880d681SAndroid Build Coastguard Worker         return nullptr;
3315*9880d681SAndroid Build Coastguard Worker     if (isa<PossiblyExactOperator>(B))
3316*9880d681SAndroid Build Coastguard Worker       if (B->isExact())
3317*9880d681SAndroid Build Coastguard Worker         return nullptr;
3318*9880d681SAndroid Build Coastguard Worker 
3319*9880d681SAndroid Build Coastguard Worker     if (MaxRecurse) {
3320*9880d681SAndroid Build Coastguard Worker       if (B->getOperand(0) == Op)
3321*9880d681SAndroid Build Coastguard Worker         return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3322*9880d681SAndroid Build Coastguard Worker                              MaxRecurse - 1);
3323*9880d681SAndroid Build Coastguard Worker       if (B->getOperand(1) == Op)
3324*9880d681SAndroid Build Coastguard Worker         return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3325*9880d681SAndroid Build Coastguard Worker                              MaxRecurse - 1);
3326*9880d681SAndroid Build Coastguard Worker     }
3327*9880d681SAndroid Build Coastguard Worker   }
3328*9880d681SAndroid Build Coastguard Worker 
3329*9880d681SAndroid Build Coastguard Worker   // Same for CmpInsts.
3330*9880d681SAndroid Build Coastguard Worker   if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3331*9880d681SAndroid Build Coastguard Worker     if (MaxRecurse) {
3332*9880d681SAndroid Build Coastguard Worker       if (C->getOperand(0) == Op)
3333*9880d681SAndroid Build Coastguard Worker         return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3334*9880d681SAndroid Build Coastguard Worker                                MaxRecurse - 1);
3335*9880d681SAndroid Build Coastguard Worker       if (C->getOperand(1) == Op)
3336*9880d681SAndroid Build Coastguard Worker         return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3337*9880d681SAndroid Build Coastguard Worker                                MaxRecurse - 1);
3338*9880d681SAndroid Build Coastguard Worker     }
3339*9880d681SAndroid Build Coastguard Worker   }
3340*9880d681SAndroid Build Coastguard Worker 
3341*9880d681SAndroid Build Coastguard Worker   // TODO: We could hand off more cases to instsimplify here.
3342*9880d681SAndroid Build Coastguard Worker 
3343*9880d681SAndroid Build Coastguard Worker   // If all operands are constant after substituting Op for RepOp then we can
3344*9880d681SAndroid Build Coastguard Worker   // constant fold the instruction.
3345*9880d681SAndroid Build Coastguard Worker   if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3346*9880d681SAndroid Build Coastguard Worker     // Build a list of all constant operands.
3347*9880d681SAndroid Build Coastguard Worker     SmallVector<Constant *, 8> ConstOps;
3348*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3349*9880d681SAndroid Build Coastguard Worker       if (I->getOperand(i) == Op)
3350*9880d681SAndroid Build Coastguard Worker         ConstOps.push_back(CRepOp);
3351*9880d681SAndroid Build Coastguard Worker       else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3352*9880d681SAndroid Build Coastguard Worker         ConstOps.push_back(COp);
3353*9880d681SAndroid Build Coastguard Worker       else
3354*9880d681SAndroid Build Coastguard Worker         break;
3355*9880d681SAndroid Build Coastguard Worker     }
3356*9880d681SAndroid Build Coastguard Worker 
3357*9880d681SAndroid Build Coastguard Worker     // All operands were constants, fold it.
3358*9880d681SAndroid Build Coastguard Worker     if (ConstOps.size() == I->getNumOperands()) {
3359*9880d681SAndroid Build Coastguard Worker       if (CmpInst *C = dyn_cast<CmpInst>(I))
3360*9880d681SAndroid Build Coastguard Worker         return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3361*9880d681SAndroid Build Coastguard Worker                                                ConstOps[1], Q.DL, Q.TLI);
3362*9880d681SAndroid Build Coastguard Worker 
3363*9880d681SAndroid Build Coastguard Worker       if (LoadInst *LI = dyn_cast<LoadInst>(I))
3364*9880d681SAndroid Build Coastguard Worker         if (!LI->isVolatile())
3365*9880d681SAndroid Build Coastguard Worker           return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
3366*9880d681SAndroid Build Coastguard Worker 
3367*9880d681SAndroid Build Coastguard Worker       return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
3368*9880d681SAndroid Build Coastguard Worker     }
3369*9880d681SAndroid Build Coastguard Worker   }
3370*9880d681SAndroid Build Coastguard Worker 
3371*9880d681SAndroid Build Coastguard Worker   return nullptr;
3372*9880d681SAndroid Build Coastguard Worker }
3373*9880d681SAndroid Build Coastguard Worker 
3374*9880d681SAndroid Build Coastguard Worker /// Given operands for a SelectInst, see if we can fold the result.
3375*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifySelectInst(Value * CondVal,Value * TrueVal,Value * FalseVal,const Query & Q,unsigned MaxRecurse)3376*9880d681SAndroid Build Coastguard Worker static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
3377*9880d681SAndroid Build Coastguard Worker                                  Value *FalseVal, const Query &Q,
3378*9880d681SAndroid Build Coastguard Worker                                  unsigned MaxRecurse) {
3379*9880d681SAndroid Build Coastguard Worker   // select true, X, Y  -> X
3380*9880d681SAndroid Build Coastguard Worker   // select false, X, Y -> Y
3381*9880d681SAndroid Build Coastguard Worker   if (Constant *CB = dyn_cast<Constant>(CondVal)) {
3382*9880d681SAndroid Build Coastguard Worker     if (CB->isAllOnesValue())
3383*9880d681SAndroid Build Coastguard Worker       return TrueVal;
3384*9880d681SAndroid Build Coastguard Worker     if (CB->isNullValue())
3385*9880d681SAndroid Build Coastguard Worker       return FalseVal;
3386*9880d681SAndroid Build Coastguard Worker   }
3387*9880d681SAndroid Build Coastguard Worker 
3388*9880d681SAndroid Build Coastguard Worker   // select C, X, X -> X
3389*9880d681SAndroid Build Coastguard Worker   if (TrueVal == FalseVal)
3390*9880d681SAndroid Build Coastguard Worker     return TrueVal;
3391*9880d681SAndroid Build Coastguard Worker 
3392*9880d681SAndroid Build Coastguard Worker   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
3393*9880d681SAndroid Build Coastguard Worker     if (isa<Constant>(TrueVal))
3394*9880d681SAndroid Build Coastguard Worker       return TrueVal;
3395*9880d681SAndroid Build Coastguard Worker     return FalseVal;
3396*9880d681SAndroid Build Coastguard Worker   }
3397*9880d681SAndroid Build Coastguard Worker   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
3398*9880d681SAndroid Build Coastguard Worker     return FalseVal;
3399*9880d681SAndroid Build Coastguard Worker   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
3400*9880d681SAndroid Build Coastguard Worker     return TrueVal;
3401*9880d681SAndroid Build Coastguard Worker 
3402*9880d681SAndroid Build Coastguard Worker   if (const auto *ICI = dyn_cast<ICmpInst>(CondVal)) {
3403*9880d681SAndroid Build Coastguard Worker     unsigned BitWidth = Q.DL.getTypeSizeInBits(TrueVal->getType());
3404*9880d681SAndroid Build Coastguard Worker     ICmpInst::Predicate Pred = ICI->getPredicate();
3405*9880d681SAndroid Build Coastguard Worker     Value *CmpLHS = ICI->getOperand(0);
3406*9880d681SAndroid Build Coastguard Worker     Value *CmpRHS = ICI->getOperand(1);
3407*9880d681SAndroid Build Coastguard Worker     APInt MinSignedValue = APInt::getSignBit(BitWidth);
3408*9880d681SAndroid Build Coastguard Worker     Value *X;
3409*9880d681SAndroid Build Coastguard Worker     const APInt *Y;
3410*9880d681SAndroid Build Coastguard Worker     bool TrueWhenUnset;
3411*9880d681SAndroid Build Coastguard Worker     bool IsBitTest = false;
3412*9880d681SAndroid Build Coastguard Worker     if (ICmpInst::isEquality(Pred) &&
3413*9880d681SAndroid Build Coastguard Worker         match(CmpLHS, m_And(m_Value(X), m_APInt(Y))) &&
3414*9880d681SAndroid Build Coastguard Worker         match(CmpRHS, m_Zero())) {
3415*9880d681SAndroid Build Coastguard Worker       IsBitTest = true;
3416*9880d681SAndroid Build Coastguard Worker       TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
3417*9880d681SAndroid Build Coastguard Worker     } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
3418*9880d681SAndroid Build Coastguard Worker       X = CmpLHS;
3419*9880d681SAndroid Build Coastguard Worker       Y = &MinSignedValue;
3420*9880d681SAndroid Build Coastguard Worker       IsBitTest = true;
3421*9880d681SAndroid Build Coastguard Worker       TrueWhenUnset = false;
3422*9880d681SAndroid Build Coastguard Worker     } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
3423*9880d681SAndroid Build Coastguard Worker       X = CmpLHS;
3424*9880d681SAndroid Build Coastguard Worker       Y = &MinSignedValue;
3425*9880d681SAndroid Build Coastguard Worker       IsBitTest = true;
3426*9880d681SAndroid Build Coastguard Worker       TrueWhenUnset = true;
3427*9880d681SAndroid Build Coastguard Worker     }
3428*9880d681SAndroid Build Coastguard Worker     if (IsBitTest) {
3429*9880d681SAndroid Build Coastguard Worker       const APInt *C;
3430*9880d681SAndroid Build Coastguard Worker       // (X & Y) == 0 ? X & ~Y : X  --> X
3431*9880d681SAndroid Build Coastguard Worker       // (X & Y) != 0 ? X & ~Y : X  --> X & ~Y
3432*9880d681SAndroid Build Coastguard Worker       if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3433*9880d681SAndroid Build Coastguard Worker           *Y == ~*C)
3434*9880d681SAndroid Build Coastguard Worker         return TrueWhenUnset ? FalseVal : TrueVal;
3435*9880d681SAndroid Build Coastguard Worker       // (X & Y) == 0 ? X : X & ~Y  --> X & ~Y
3436*9880d681SAndroid Build Coastguard Worker       // (X & Y) != 0 ? X : X & ~Y  --> X
3437*9880d681SAndroid Build Coastguard Worker       if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3438*9880d681SAndroid Build Coastguard Worker           *Y == ~*C)
3439*9880d681SAndroid Build Coastguard Worker         return TrueWhenUnset ? FalseVal : TrueVal;
3440*9880d681SAndroid Build Coastguard Worker 
3441*9880d681SAndroid Build Coastguard Worker       if (Y->isPowerOf2()) {
3442*9880d681SAndroid Build Coastguard Worker         // (X & Y) == 0 ? X | Y : X  --> X | Y
3443*9880d681SAndroid Build Coastguard Worker         // (X & Y) != 0 ? X | Y : X  --> X
3444*9880d681SAndroid Build Coastguard Worker         if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3445*9880d681SAndroid Build Coastguard Worker             *Y == *C)
3446*9880d681SAndroid Build Coastguard Worker           return TrueWhenUnset ? TrueVal : FalseVal;
3447*9880d681SAndroid Build Coastguard Worker         // (X & Y) == 0 ? X : X | Y  --> X
3448*9880d681SAndroid Build Coastguard Worker         // (X & Y) != 0 ? X : X | Y  --> X | Y
3449*9880d681SAndroid Build Coastguard Worker         if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3450*9880d681SAndroid Build Coastguard Worker             *Y == *C)
3451*9880d681SAndroid Build Coastguard Worker           return TrueWhenUnset ? TrueVal : FalseVal;
3452*9880d681SAndroid Build Coastguard Worker       }
3453*9880d681SAndroid Build Coastguard Worker     }
3454*9880d681SAndroid Build Coastguard Worker     if (ICI->hasOneUse()) {
3455*9880d681SAndroid Build Coastguard Worker       const APInt *C;
3456*9880d681SAndroid Build Coastguard Worker       if (match(CmpRHS, m_APInt(C))) {
3457*9880d681SAndroid Build Coastguard Worker         // X < MIN ? T : F  -->  F
3458*9880d681SAndroid Build Coastguard Worker         if (Pred == ICmpInst::ICMP_SLT && C->isMinSignedValue())
3459*9880d681SAndroid Build Coastguard Worker           return FalseVal;
3460*9880d681SAndroid Build Coastguard Worker         // X < MIN ? T : F  -->  F
3461*9880d681SAndroid Build Coastguard Worker         if (Pred == ICmpInst::ICMP_ULT && C->isMinValue())
3462*9880d681SAndroid Build Coastguard Worker           return FalseVal;
3463*9880d681SAndroid Build Coastguard Worker         // X > MAX ? T : F  -->  F
3464*9880d681SAndroid Build Coastguard Worker         if (Pred == ICmpInst::ICMP_SGT && C->isMaxSignedValue())
3465*9880d681SAndroid Build Coastguard Worker           return FalseVal;
3466*9880d681SAndroid Build Coastguard Worker         // X > MAX ? T : F  -->  F
3467*9880d681SAndroid Build Coastguard Worker         if (Pred == ICmpInst::ICMP_UGT && C->isMaxValue())
3468*9880d681SAndroid Build Coastguard Worker           return FalseVal;
3469*9880d681SAndroid Build Coastguard Worker       }
3470*9880d681SAndroid Build Coastguard Worker     }
3471*9880d681SAndroid Build Coastguard Worker 
3472*9880d681SAndroid Build Coastguard Worker     // If we have an equality comparison then we know the value in one of the
3473*9880d681SAndroid Build Coastguard Worker     // arms of the select. See if substituting this value into the arm and
3474*9880d681SAndroid Build Coastguard Worker     // simplifying the result yields the same value as the other arm.
3475*9880d681SAndroid Build Coastguard Worker     if (Pred == ICmpInst::ICMP_EQ) {
3476*9880d681SAndroid Build Coastguard Worker       if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3477*9880d681SAndroid Build Coastguard Worker               TrueVal ||
3478*9880d681SAndroid Build Coastguard Worker           SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3479*9880d681SAndroid Build Coastguard Worker               TrueVal)
3480*9880d681SAndroid Build Coastguard Worker         return FalseVal;
3481*9880d681SAndroid Build Coastguard Worker       if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3482*9880d681SAndroid Build Coastguard Worker               FalseVal ||
3483*9880d681SAndroid Build Coastguard Worker           SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3484*9880d681SAndroid Build Coastguard Worker               FalseVal)
3485*9880d681SAndroid Build Coastguard Worker         return FalseVal;
3486*9880d681SAndroid Build Coastguard Worker     } else if (Pred == ICmpInst::ICMP_NE) {
3487*9880d681SAndroid Build Coastguard Worker       if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3488*9880d681SAndroid Build Coastguard Worker               FalseVal ||
3489*9880d681SAndroid Build Coastguard Worker           SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3490*9880d681SAndroid Build Coastguard Worker               FalseVal)
3491*9880d681SAndroid Build Coastguard Worker         return TrueVal;
3492*9880d681SAndroid Build Coastguard Worker       if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3493*9880d681SAndroid Build Coastguard Worker               TrueVal ||
3494*9880d681SAndroid Build Coastguard Worker           SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3495*9880d681SAndroid Build Coastguard Worker               TrueVal)
3496*9880d681SAndroid Build Coastguard Worker         return TrueVal;
3497*9880d681SAndroid Build Coastguard Worker     }
3498*9880d681SAndroid Build Coastguard Worker   }
3499*9880d681SAndroid Build Coastguard Worker 
3500*9880d681SAndroid Build Coastguard Worker   return nullptr;
3501*9880d681SAndroid Build Coastguard Worker }
3502*9880d681SAndroid Build Coastguard Worker 
SimplifySelectInst(Value * Cond,Value * TrueVal,Value * FalseVal,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)3503*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
3504*9880d681SAndroid Build Coastguard Worker                                 const DataLayout &DL,
3505*9880d681SAndroid Build Coastguard Worker                                 const TargetLibraryInfo *TLI,
3506*9880d681SAndroid Build Coastguard Worker                                 const DominatorTree *DT, AssumptionCache *AC,
3507*9880d681SAndroid Build Coastguard Worker                                 const Instruction *CxtI) {
3508*9880d681SAndroid Build Coastguard Worker   return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
3509*9880d681SAndroid Build Coastguard Worker                               Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
3510*9880d681SAndroid Build Coastguard Worker }
3511*9880d681SAndroid Build Coastguard Worker 
3512*9880d681SAndroid Build Coastguard Worker /// Given operands for an GetElementPtrInst, see if we can fold the result.
3513*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifyGEPInst(Type * SrcTy,ArrayRef<Value * > Ops,const Query & Q,unsigned)3514*9880d681SAndroid Build Coastguard Worker static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3515*9880d681SAndroid Build Coastguard Worker                               const Query &Q, unsigned) {
3516*9880d681SAndroid Build Coastguard Worker   // The type of the GEP pointer operand.
3517*9880d681SAndroid Build Coastguard Worker   unsigned AS =
3518*9880d681SAndroid Build Coastguard Worker       cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
3519*9880d681SAndroid Build Coastguard Worker 
3520*9880d681SAndroid Build Coastguard Worker   // getelementptr P -> P.
3521*9880d681SAndroid Build Coastguard Worker   if (Ops.size() == 1)
3522*9880d681SAndroid Build Coastguard Worker     return Ops[0];
3523*9880d681SAndroid Build Coastguard Worker 
3524*9880d681SAndroid Build Coastguard Worker   // Compute the (pointer) type returned by the GEP instruction.
3525*9880d681SAndroid Build Coastguard Worker   Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
3526*9880d681SAndroid Build Coastguard Worker   Type *GEPTy = PointerType::get(LastType, AS);
3527*9880d681SAndroid Build Coastguard Worker   if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3528*9880d681SAndroid Build Coastguard Worker     GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3529*9880d681SAndroid Build Coastguard Worker 
3530*9880d681SAndroid Build Coastguard Worker   if (isa<UndefValue>(Ops[0]))
3531*9880d681SAndroid Build Coastguard Worker     return UndefValue::get(GEPTy);
3532*9880d681SAndroid Build Coastguard Worker 
3533*9880d681SAndroid Build Coastguard Worker   if (Ops.size() == 2) {
3534*9880d681SAndroid Build Coastguard Worker     // getelementptr P, 0 -> P.
3535*9880d681SAndroid Build Coastguard Worker     if (match(Ops[1], m_Zero()))
3536*9880d681SAndroid Build Coastguard Worker       return Ops[0];
3537*9880d681SAndroid Build Coastguard Worker 
3538*9880d681SAndroid Build Coastguard Worker     Type *Ty = SrcTy;
3539*9880d681SAndroid Build Coastguard Worker     if (Ty->isSized()) {
3540*9880d681SAndroid Build Coastguard Worker       Value *P;
3541*9880d681SAndroid Build Coastguard Worker       uint64_t C;
3542*9880d681SAndroid Build Coastguard Worker       uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
3543*9880d681SAndroid Build Coastguard Worker       // getelementptr P, N -> P if P points to a type of zero size.
3544*9880d681SAndroid Build Coastguard Worker       if (TyAllocSize == 0)
3545*9880d681SAndroid Build Coastguard Worker         return Ops[0];
3546*9880d681SAndroid Build Coastguard Worker 
3547*9880d681SAndroid Build Coastguard Worker       // The following transforms are only safe if the ptrtoint cast
3548*9880d681SAndroid Build Coastguard Worker       // doesn't truncate the pointers.
3549*9880d681SAndroid Build Coastguard Worker       if (Ops[1]->getType()->getScalarSizeInBits() ==
3550*9880d681SAndroid Build Coastguard Worker           Q.DL.getPointerSizeInBits(AS)) {
3551*9880d681SAndroid Build Coastguard Worker         auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3552*9880d681SAndroid Build Coastguard Worker           if (match(P, m_Zero()))
3553*9880d681SAndroid Build Coastguard Worker             return Constant::getNullValue(GEPTy);
3554*9880d681SAndroid Build Coastguard Worker           Value *Temp;
3555*9880d681SAndroid Build Coastguard Worker           if (match(P, m_PtrToInt(m_Value(Temp))))
3556*9880d681SAndroid Build Coastguard Worker             if (Temp->getType() == GEPTy)
3557*9880d681SAndroid Build Coastguard Worker               return Temp;
3558*9880d681SAndroid Build Coastguard Worker           return nullptr;
3559*9880d681SAndroid Build Coastguard Worker         };
3560*9880d681SAndroid Build Coastguard Worker 
3561*9880d681SAndroid Build Coastguard Worker         // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3562*9880d681SAndroid Build Coastguard Worker         if (TyAllocSize == 1 &&
3563*9880d681SAndroid Build Coastguard Worker             match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3564*9880d681SAndroid Build Coastguard Worker           if (Value *R = PtrToIntOrZero(P))
3565*9880d681SAndroid Build Coastguard Worker             return R;
3566*9880d681SAndroid Build Coastguard Worker 
3567*9880d681SAndroid Build Coastguard Worker         // getelementptr V, (ashr (sub P, V), C) -> Q
3568*9880d681SAndroid Build Coastguard Worker         // if P points to a type of size 1 << C.
3569*9880d681SAndroid Build Coastguard Worker         if (match(Ops[1],
3570*9880d681SAndroid Build Coastguard Worker                   m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3571*9880d681SAndroid Build Coastguard Worker                          m_ConstantInt(C))) &&
3572*9880d681SAndroid Build Coastguard Worker             TyAllocSize == 1ULL << C)
3573*9880d681SAndroid Build Coastguard Worker           if (Value *R = PtrToIntOrZero(P))
3574*9880d681SAndroid Build Coastguard Worker             return R;
3575*9880d681SAndroid Build Coastguard Worker 
3576*9880d681SAndroid Build Coastguard Worker         // getelementptr V, (sdiv (sub P, V), C) -> Q
3577*9880d681SAndroid Build Coastguard Worker         // if P points to a type of size C.
3578*9880d681SAndroid Build Coastguard Worker         if (match(Ops[1],
3579*9880d681SAndroid Build Coastguard Worker                   m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3580*9880d681SAndroid Build Coastguard Worker                          m_SpecificInt(TyAllocSize))))
3581*9880d681SAndroid Build Coastguard Worker           if (Value *R = PtrToIntOrZero(P))
3582*9880d681SAndroid Build Coastguard Worker             return R;
3583*9880d681SAndroid Build Coastguard Worker       }
3584*9880d681SAndroid Build Coastguard Worker     }
3585*9880d681SAndroid Build Coastguard Worker   }
3586*9880d681SAndroid Build Coastguard Worker 
3587*9880d681SAndroid Build Coastguard Worker   // Check to see if this is constant foldable.
3588*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3589*9880d681SAndroid Build Coastguard Worker     if (!isa<Constant>(Ops[i]))
3590*9880d681SAndroid Build Coastguard Worker       return nullptr;
3591*9880d681SAndroid Build Coastguard Worker 
3592*9880d681SAndroid Build Coastguard Worker   return ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3593*9880d681SAndroid Build Coastguard Worker                                         Ops.slice(1));
3594*9880d681SAndroid Build Coastguard Worker }
3595*9880d681SAndroid Build Coastguard Worker 
SimplifyGEPInst(Type * SrcTy,ArrayRef<Value * > Ops,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)3596*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3597*9880d681SAndroid Build Coastguard Worker                              const DataLayout &DL,
3598*9880d681SAndroid Build Coastguard Worker                              const TargetLibraryInfo *TLI,
3599*9880d681SAndroid Build Coastguard Worker                              const DominatorTree *DT, AssumptionCache *AC,
3600*9880d681SAndroid Build Coastguard Worker                              const Instruction *CxtI) {
3601*9880d681SAndroid Build Coastguard Worker   return ::SimplifyGEPInst(SrcTy, Ops,
3602*9880d681SAndroid Build Coastguard Worker                            Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
3603*9880d681SAndroid Build Coastguard Worker }
3604*9880d681SAndroid Build Coastguard Worker 
3605*9880d681SAndroid Build Coastguard Worker /// Given operands for an InsertValueInst, see if we can fold the result.
3606*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifyInsertValueInst(Value * Agg,Value * Val,ArrayRef<unsigned> Idxs,const Query & Q,unsigned)3607*9880d681SAndroid Build Coastguard Worker static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3608*9880d681SAndroid Build Coastguard Worker                                       ArrayRef<unsigned> Idxs, const Query &Q,
3609*9880d681SAndroid Build Coastguard Worker                                       unsigned) {
3610*9880d681SAndroid Build Coastguard Worker   if (Constant *CAgg = dyn_cast<Constant>(Agg))
3611*9880d681SAndroid Build Coastguard Worker     if (Constant *CVal = dyn_cast<Constant>(Val))
3612*9880d681SAndroid Build Coastguard Worker       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3613*9880d681SAndroid Build Coastguard Worker 
3614*9880d681SAndroid Build Coastguard Worker   // insertvalue x, undef, n -> x
3615*9880d681SAndroid Build Coastguard Worker   if (match(Val, m_Undef()))
3616*9880d681SAndroid Build Coastguard Worker     return Agg;
3617*9880d681SAndroid Build Coastguard Worker 
3618*9880d681SAndroid Build Coastguard Worker   // insertvalue x, (extractvalue y, n), n
3619*9880d681SAndroid Build Coastguard Worker   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
3620*9880d681SAndroid Build Coastguard Worker     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3621*9880d681SAndroid Build Coastguard Worker         EV->getIndices() == Idxs) {
3622*9880d681SAndroid Build Coastguard Worker       // insertvalue undef, (extractvalue y, n), n -> y
3623*9880d681SAndroid Build Coastguard Worker       if (match(Agg, m_Undef()))
3624*9880d681SAndroid Build Coastguard Worker         return EV->getAggregateOperand();
3625*9880d681SAndroid Build Coastguard Worker 
3626*9880d681SAndroid Build Coastguard Worker       // insertvalue y, (extractvalue y, n), n -> y
3627*9880d681SAndroid Build Coastguard Worker       if (Agg == EV->getAggregateOperand())
3628*9880d681SAndroid Build Coastguard Worker         return Agg;
3629*9880d681SAndroid Build Coastguard Worker     }
3630*9880d681SAndroid Build Coastguard Worker 
3631*9880d681SAndroid Build Coastguard Worker   return nullptr;
3632*9880d681SAndroid Build Coastguard Worker }
3633*9880d681SAndroid Build Coastguard Worker 
SimplifyInsertValueInst(Value * Agg,Value * Val,ArrayRef<unsigned> Idxs,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)3634*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyInsertValueInst(
3635*9880d681SAndroid Build Coastguard Worker     Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, const DataLayout &DL,
3636*9880d681SAndroid Build Coastguard Worker     const TargetLibraryInfo *TLI, const DominatorTree *DT, AssumptionCache *AC,
3637*9880d681SAndroid Build Coastguard Worker     const Instruction *CxtI) {
3638*9880d681SAndroid Build Coastguard Worker   return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query(DL, TLI, DT, AC, CxtI),
3639*9880d681SAndroid Build Coastguard Worker                                    RecursionLimit);
3640*9880d681SAndroid Build Coastguard Worker }
3641*9880d681SAndroid Build Coastguard Worker 
3642*9880d681SAndroid Build Coastguard Worker /// Given operands for an ExtractValueInst, see if we can fold the result.
3643*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifyExtractValueInst(Value * Agg,ArrayRef<unsigned> Idxs,const Query &,unsigned)3644*9880d681SAndroid Build Coastguard Worker static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3645*9880d681SAndroid Build Coastguard Worker                                        const Query &, unsigned) {
3646*9880d681SAndroid Build Coastguard Worker   if (auto *CAgg = dyn_cast<Constant>(Agg))
3647*9880d681SAndroid Build Coastguard Worker     return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3648*9880d681SAndroid Build Coastguard Worker 
3649*9880d681SAndroid Build Coastguard Worker   // extractvalue x, (insertvalue y, elt, n), n -> elt
3650*9880d681SAndroid Build Coastguard Worker   unsigned NumIdxs = Idxs.size();
3651*9880d681SAndroid Build Coastguard Worker   for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3652*9880d681SAndroid Build Coastguard Worker        IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3653*9880d681SAndroid Build Coastguard Worker     ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3654*9880d681SAndroid Build Coastguard Worker     unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3655*9880d681SAndroid Build Coastguard Worker     unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3656*9880d681SAndroid Build Coastguard Worker     if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3657*9880d681SAndroid Build Coastguard Worker         Idxs.slice(0, NumCommonIdxs)) {
3658*9880d681SAndroid Build Coastguard Worker       if (NumIdxs == NumInsertValueIdxs)
3659*9880d681SAndroid Build Coastguard Worker         return IVI->getInsertedValueOperand();
3660*9880d681SAndroid Build Coastguard Worker       break;
3661*9880d681SAndroid Build Coastguard Worker     }
3662*9880d681SAndroid Build Coastguard Worker   }
3663*9880d681SAndroid Build Coastguard Worker 
3664*9880d681SAndroid Build Coastguard Worker   return nullptr;
3665*9880d681SAndroid Build Coastguard Worker }
3666*9880d681SAndroid Build Coastguard Worker 
SimplifyExtractValueInst(Value * Agg,ArrayRef<unsigned> Idxs,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)3667*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3668*9880d681SAndroid Build Coastguard Worker                                       const DataLayout &DL,
3669*9880d681SAndroid Build Coastguard Worker                                       const TargetLibraryInfo *TLI,
3670*9880d681SAndroid Build Coastguard Worker                                       const DominatorTree *DT,
3671*9880d681SAndroid Build Coastguard Worker                                       AssumptionCache *AC,
3672*9880d681SAndroid Build Coastguard Worker                                       const Instruction *CxtI) {
3673*9880d681SAndroid Build Coastguard Worker   return ::SimplifyExtractValueInst(Agg, Idxs, Query(DL, TLI, DT, AC, CxtI),
3674*9880d681SAndroid Build Coastguard Worker                                     RecursionLimit);
3675*9880d681SAndroid Build Coastguard Worker }
3676*9880d681SAndroid Build Coastguard Worker 
3677*9880d681SAndroid Build Coastguard Worker /// Given operands for an ExtractElementInst, see if we can fold the result.
3678*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifyExtractElementInst(Value * Vec,Value * Idx,const Query &,unsigned)3679*9880d681SAndroid Build Coastguard Worker static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const Query &,
3680*9880d681SAndroid Build Coastguard Worker                                          unsigned) {
3681*9880d681SAndroid Build Coastguard Worker   if (auto *CVec = dyn_cast<Constant>(Vec)) {
3682*9880d681SAndroid Build Coastguard Worker     if (auto *CIdx = dyn_cast<Constant>(Idx))
3683*9880d681SAndroid Build Coastguard Worker       return ConstantFoldExtractElementInstruction(CVec, CIdx);
3684*9880d681SAndroid Build Coastguard Worker 
3685*9880d681SAndroid Build Coastguard Worker     // The index is not relevant if our vector is a splat.
3686*9880d681SAndroid Build Coastguard Worker     if (auto *Splat = CVec->getSplatValue())
3687*9880d681SAndroid Build Coastguard Worker       return Splat;
3688*9880d681SAndroid Build Coastguard Worker 
3689*9880d681SAndroid Build Coastguard Worker     if (isa<UndefValue>(Vec))
3690*9880d681SAndroid Build Coastguard Worker       return UndefValue::get(Vec->getType()->getVectorElementType());
3691*9880d681SAndroid Build Coastguard Worker   }
3692*9880d681SAndroid Build Coastguard Worker 
3693*9880d681SAndroid Build Coastguard Worker   // If extracting a specified index from the vector, see if we can recursively
3694*9880d681SAndroid Build Coastguard Worker   // find a previously computed scalar that was inserted into the vector.
3695*9880d681SAndroid Build Coastguard Worker   if (auto *IdxC = dyn_cast<ConstantInt>(Idx))
3696*9880d681SAndroid Build Coastguard Worker     if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
3697*9880d681SAndroid Build Coastguard Worker       return Elt;
3698*9880d681SAndroid Build Coastguard Worker 
3699*9880d681SAndroid Build Coastguard Worker   return nullptr;
3700*9880d681SAndroid Build Coastguard Worker }
3701*9880d681SAndroid Build Coastguard Worker 
SimplifyExtractElementInst(Value * Vec,Value * Idx,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)3702*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyExtractElementInst(
3703*9880d681SAndroid Build Coastguard Worker     Value *Vec, Value *Idx, const DataLayout &DL, const TargetLibraryInfo *TLI,
3704*9880d681SAndroid Build Coastguard Worker     const DominatorTree *DT, AssumptionCache *AC, const Instruction *CxtI) {
3705*9880d681SAndroid Build Coastguard Worker   return ::SimplifyExtractElementInst(Vec, Idx, Query(DL, TLI, DT, AC, CxtI),
3706*9880d681SAndroid Build Coastguard Worker                                       RecursionLimit);
3707*9880d681SAndroid Build Coastguard Worker }
3708*9880d681SAndroid Build Coastguard Worker 
3709*9880d681SAndroid Build Coastguard Worker /// See if we can fold the given phi. If not, returns null.
SimplifyPHINode(PHINode * PN,const Query & Q)3710*9880d681SAndroid Build Coastguard Worker static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
3711*9880d681SAndroid Build Coastguard Worker   // If all of the PHI's incoming values are the same then replace the PHI node
3712*9880d681SAndroid Build Coastguard Worker   // with the common value.
3713*9880d681SAndroid Build Coastguard Worker   Value *CommonValue = nullptr;
3714*9880d681SAndroid Build Coastguard Worker   bool HasUndefInput = false;
3715*9880d681SAndroid Build Coastguard Worker   for (Value *Incoming : PN->incoming_values()) {
3716*9880d681SAndroid Build Coastguard Worker     // If the incoming value is the phi node itself, it can safely be skipped.
3717*9880d681SAndroid Build Coastguard Worker     if (Incoming == PN) continue;
3718*9880d681SAndroid Build Coastguard Worker     if (isa<UndefValue>(Incoming)) {
3719*9880d681SAndroid Build Coastguard Worker       // Remember that we saw an undef value, but otherwise ignore them.
3720*9880d681SAndroid Build Coastguard Worker       HasUndefInput = true;
3721*9880d681SAndroid Build Coastguard Worker       continue;
3722*9880d681SAndroid Build Coastguard Worker     }
3723*9880d681SAndroid Build Coastguard Worker     if (CommonValue && Incoming != CommonValue)
3724*9880d681SAndroid Build Coastguard Worker       return nullptr;  // Not the same, bail out.
3725*9880d681SAndroid Build Coastguard Worker     CommonValue = Incoming;
3726*9880d681SAndroid Build Coastguard Worker   }
3727*9880d681SAndroid Build Coastguard Worker 
3728*9880d681SAndroid Build Coastguard Worker   // If CommonValue is null then all of the incoming values were either undef or
3729*9880d681SAndroid Build Coastguard Worker   // equal to the phi node itself.
3730*9880d681SAndroid Build Coastguard Worker   if (!CommonValue)
3731*9880d681SAndroid Build Coastguard Worker     return UndefValue::get(PN->getType());
3732*9880d681SAndroid Build Coastguard Worker 
3733*9880d681SAndroid Build Coastguard Worker   // If we have a PHI node like phi(X, undef, X), where X is defined by some
3734*9880d681SAndroid Build Coastguard Worker   // instruction, we cannot return X as the result of the PHI node unless it
3735*9880d681SAndroid Build Coastguard Worker   // dominates the PHI block.
3736*9880d681SAndroid Build Coastguard Worker   if (HasUndefInput)
3737*9880d681SAndroid Build Coastguard Worker     return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
3738*9880d681SAndroid Build Coastguard Worker 
3739*9880d681SAndroid Build Coastguard Worker   return CommonValue;
3740*9880d681SAndroid Build Coastguard Worker }
3741*9880d681SAndroid Build Coastguard Worker 
SimplifyTruncInst(Value * Op,Type * Ty,const Query & Q,unsigned)3742*9880d681SAndroid Build Coastguard Worker static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
3743*9880d681SAndroid Build Coastguard Worker   if (Constant *C = dyn_cast<Constant>(Op))
3744*9880d681SAndroid Build Coastguard Worker     return ConstantFoldCastOperand(Instruction::Trunc, C, Ty, Q.DL);
3745*9880d681SAndroid Build Coastguard Worker 
3746*9880d681SAndroid Build Coastguard Worker   return nullptr;
3747*9880d681SAndroid Build Coastguard Worker }
3748*9880d681SAndroid Build Coastguard Worker 
SimplifyTruncInst(Value * Op,Type * Ty,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)3749*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout &DL,
3750*9880d681SAndroid Build Coastguard Worker                                const TargetLibraryInfo *TLI,
3751*9880d681SAndroid Build Coastguard Worker                                const DominatorTree *DT, AssumptionCache *AC,
3752*9880d681SAndroid Build Coastguard Worker                                const Instruction *CxtI) {
3753*9880d681SAndroid Build Coastguard Worker   return ::SimplifyTruncInst(Op, Ty, Query(DL, TLI, DT, AC, CxtI),
3754*9880d681SAndroid Build Coastguard Worker                              RecursionLimit);
3755*9880d681SAndroid Build Coastguard Worker }
3756*9880d681SAndroid Build Coastguard Worker 
3757*9880d681SAndroid Build Coastguard Worker //=== Helper functions for higher up the class hierarchy.
3758*9880d681SAndroid Build Coastguard Worker 
3759*9880d681SAndroid Build Coastguard Worker /// Given operands for a BinaryOperator, see if we can fold the result.
3760*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifyBinOp(unsigned Opcode,Value * LHS,Value * RHS,const Query & Q,unsigned MaxRecurse)3761*9880d681SAndroid Build Coastguard Worker static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3762*9880d681SAndroid Build Coastguard Worker                             const Query &Q, unsigned MaxRecurse) {
3763*9880d681SAndroid Build Coastguard Worker   switch (Opcode) {
3764*9880d681SAndroid Build Coastguard Worker   case Instruction::Add:
3765*9880d681SAndroid Build Coastguard Worker     return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3766*9880d681SAndroid Build Coastguard Worker                            Q, MaxRecurse);
3767*9880d681SAndroid Build Coastguard Worker   case Instruction::FAdd:
3768*9880d681SAndroid Build Coastguard Worker     return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3769*9880d681SAndroid Build Coastguard Worker 
3770*9880d681SAndroid Build Coastguard Worker   case Instruction::Sub:
3771*9880d681SAndroid Build Coastguard Worker     return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3772*9880d681SAndroid Build Coastguard Worker                            Q, MaxRecurse);
3773*9880d681SAndroid Build Coastguard Worker   case Instruction::FSub:
3774*9880d681SAndroid Build Coastguard Worker     return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3775*9880d681SAndroid Build Coastguard Worker 
3776*9880d681SAndroid Build Coastguard Worker   case Instruction::Mul:  return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
3777*9880d681SAndroid Build Coastguard Worker   case Instruction::FMul:
3778*9880d681SAndroid Build Coastguard Worker     return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3779*9880d681SAndroid Build Coastguard Worker   case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
3780*9880d681SAndroid Build Coastguard Worker   case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
3781*9880d681SAndroid Build Coastguard Worker   case Instruction::FDiv:
3782*9880d681SAndroid Build Coastguard Worker       return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3783*9880d681SAndroid Build Coastguard Worker   case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
3784*9880d681SAndroid Build Coastguard Worker   case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
3785*9880d681SAndroid Build Coastguard Worker   case Instruction::FRem:
3786*9880d681SAndroid Build Coastguard Worker       return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3787*9880d681SAndroid Build Coastguard Worker   case Instruction::Shl:
3788*9880d681SAndroid Build Coastguard Worker     return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3789*9880d681SAndroid Build Coastguard Worker                            Q, MaxRecurse);
3790*9880d681SAndroid Build Coastguard Worker   case Instruction::LShr:
3791*9880d681SAndroid Build Coastguard Worker     return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3792*9880d681SAndroid Build Coastguard Worker   case Instruction::AShr:
3793*9880d681SAndroid Build Coastguard Worker     return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3794*9880d681SAndroid Build Coastguard Worker   case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
3795*9880d681SAndroid Build Coastguard Worker   case Instruction::Or:  return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
3796*9880d681SAndroid Build Coastguard Worker   case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
3797*9880d681SAndroid Build Coastguard Worker   default:
3798*9880d681SAndroid Build Coastguard Worker     if (Constant *CLHS = dyn_cast<Constant>(LHS))
3799*9880d681SAndroid Build Coastguard Worker       if (Constant *CRHS = dyn_cast<Constant>(RHS))
3800*9880d681SAndroid Build Coastguard Worker         return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
3801*9880d681SAndroid Build Coastguard Worker 
3802*9880d681SAndroid Build Coastguard Worker     // If the operation is associative, try some generic simplifications.
3803*9880d681SAndroid Build Coastguard Worker     if (Instruction::isAssociative(Opcode))
3804*9880d681SAndroid Build Coastguard Worker       if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
3805*9880d681SAndroid Build Coastguard Worker         return V;
3806*9880d681SAndroid Build Coastguard Worker 
3807*9880d681SAndroid Build Coastguard Worker     // If the operation is with the result of a select instruction check whether
3808*9880d681SAndroid Build Coastguard Worker     // operating on either branch of the select always yields the same value.
3809*9880d681SAndroid Build Coastguard Worker     if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3810*9880d681SAndroid Build Coastguard Worker       if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
3811*9880d681SAndroid Build Coastguard Worker         return V;
3812*9880d681SAndroid Build Coastguard Worker 
3813*9880d681SAndroid Build Coastguard Worker     // If the operation is with the result of a phi instruction, check whether
3814*9880d681SAndroid Build Coastguard Worker     // operating on all incoming values of the phi always yields the same value.
3815*9880d681SAndroid Build Coastguard Worker     if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3816*9880d681SAndroid Build Coastguard Worker       if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
3817*9880d681SAndroid Build Coastguard Worker         return V;
3818*9880d681SAndroid Build Coastguard Worker 
3819*9880d681SAndroid Build Coastguard Worker     return nullptr;
3820*9880d681SAndroid Build Coastguard Worker   }
3821*9880d681SAndroid Build Coastguard Worker }
3822*9880d681SAndroid Build Coastguard Worker 
3823*9880d681SAndroid Build Coastguard Worker /// Given operands for a BinaryOperator, see if we can fold the result.
3824*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
3825*9880d681SAndroid Build Coastguard Worker /// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
3826*9880d681SAndroid Build Coastguard Worker /// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
SimplifyFPBinOp(unsigned Opcode,Value * LHS,Value * RHS,const FastMathFlags & FMF,const Query & Q,unsigned MaxRecurse)3827*9880d681SAndroid Build Coastguard Worker static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3828*9880d681SAndroid Build Coastguard Worker                               const FastMathFlags &FMF, const Query &Q,
3829*9880d681SAndroid Build Coastguard Worker                               unsigned MaxRecurse) {
3830*9880d681SAndroid Build Coastguard Worker   switch (Opcode) {
3831*9880d681SAndroid Build Coastguard Worker   case Instruction::FAdd:
3832*9880d681SAndroid Build Coastguard Worker     return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
3833*9880d681SAndroid Build Coastguard Worker   case Instruction::FSub:
3834*9880d681SAndroid Build Coastguard Worker     return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
3835*9880d681SAndroid Build Coastguard Worker   case Instruction::FMul:
3836*9880d681SAndroid Build Coastguard Worker     return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
3837*9880d681SAndroid Build Coastguard Worker   default:
3838*9880d681SAndroid Build Coastguard Worker     return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
3839*9880d681SAndroid Build Coastguard Worker   }
3840*9880d681SAndroid Build Coastguard Worker }
3841*9880d681SAndroid Build Coastguard Worker 
SimplifyBinOp(unsigned Opcode,Value * LHS,Value * RHS,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)3842*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3843*9880d681SAndroid Build Coastguard Worker                            const DataLayout &DL, const TargetLibraryInfo *TLI,
3844*9880d681SAndroid Build Coastguard Worker                            const DominatorTree *DT, AssumptionCache *AC,
3845*9880d681SAndroid Build Coastguard Worker                            const Instruction *CxtI) {
3846*9880d681SAndroid Build Coastguard Worker   return ::SimplifyBinOp(Opcode, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
3847*9880d681SAndroid Build Coastguard Worker                          RecursionLimit);
3848*9880d681SAndroid Build Coastguard Worker }
3849*9880d681SAndroid Build Coastguard Worker 
SimplifyFPBinOp(unsigned Opcode,Value * LHS,Value * RHS,const FastMathFlags & FMF,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)3850*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3851*9880d681SAndroid Build Coastguard Worker                              const FastMathFlags &FMF, const DataLayout &DL,
3852*9880d681SAndroid Build Coastguard Worker                              const TargetLibraryInfo *TLI,
3853*9880d681SAndroid Build Coastguard Worker                              const DominatorTree *DT, AssumptionCache *AC,
3854*9880d681SAndroid Build Coastguard Worker                              const Instruction *CxtI) {
3855*9880d681SAndroid Build Coastguard Worker   return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Query(DL, TLI, DT, AC, CxtI),
3856*9880d681SAndroid Build Coastguard Worker                            RecursionLimit);
3857*9880d681SAndroid Build Coastguard Worker }
3858*9880d681SAndroid Build Coastguard Worker 
3859*9880d681SAndroid Build Coastguard Worker /// Given operands for a CmpInst, see if we can fold the result.
SimplifyCmpInst(unsigned Predicate,Value * LHS,Value * RHS,const Query & Q,unsigned MaxRecurse)3860*9880d681SAndroid Build Coastguard Worker static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3861*9880d681SAndroid Build Coastguard Worker                               const Query &Q, unsigned MaxRecurse) {
3862*9880d681SAndroid Build Coastguard Worker   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
3863*9880d681SAndroid Build Coastguard Worker     return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
3864*9880d681SAndroid Build Coastguard Worker   return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3865*9880d681SAndroid Build Coastguard Worker }
3866*9880d681SAndroid Build Coastguard Worker 
SimplifyCmpInst(unsigned Predicate,Value * LHS,Value * RHS,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)3867*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3868*9880d681SAndroid Build Coastguard Worker                              const DataLayout &DL, const TargetLibraryInfo *TLI,
3869*9880d681SAndroid Build Coastguard Worker                              const DominatorTree *DT, AssumptionCache *AC,
3870*9880d681SAndroid Build Coastguard Worker                              const Instruction *CxtI) {
3871*9880d681SAndroid Build Coastguard Worker   return ::SimplifyCmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
3872*9880d681SAndroid Build Coastguard Worker                            RecursionLimit);
3873*9880d681SAndroid Build Coastguard Worker }
3874*9880d681SAndroid Build Coastguard Worker 
IsIdempotent(Intrinsic::ID ID)3875*9880d681SAndroid Build Coastguard Worker static bool IsIdempotent(Intrinsic::ID ID) {
3876*9880d681SAndroid Build Coastguard Worker   switch (ID) {
3877*9880d681SAndroid Build Coastguard Worker   default: return false;
3878*9880d681SAndroid Build Coastguard Worker 
3879*9880d681SAndroid Build Coastguard Worker   // Unary idempotent: f(f(x)) = f(x)
3880*9880d681SAndroid Build Coastguard Worker   case Intrinsic::fabs:
3881*9880d681SAndroid Build Coastguard Worker   case Intrinsic::floor:
3882*9880d681SAndroid Build Coastguard Worker   case Intrinsic::ceil:
3883*9880d681SAndroid Build Coastguard Worker   case Intrinsic::trunc:
3884*9880d681SAndroid Build Coastguard Worker   case Intrinsic::rint:
3885*9880d681SAndroid Build Coastguard Worker   case Intrinsic::nearbyint:
3886*9880d681SAndroid Build Coastguard Worker   case Intrinsic::round:
3887*9880d681SAndroid Build Coastguard Worker     return true;
3888*9880d681SAndroid Build Coastguard Worker   }
3889*9880d681SAndroid Build Coastguard Worker }
3890*9880d681SAndroid Build Coastguard Worker 
SimplifyRelativeLoad(Constant * Ptr,Constant * Offset,const DataLayout & DL)3891*9880d681SAndroid Build Coastguard Worker static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
3892*9880d681SAndroid Build Coastguard Worker                                    const DataLayout &DL) {
3893*9880d681SAndroid Build Coastguard Worker   GlobalValue *PtrSym;
3894*9880d681SAndroid Build Coastguard Worker   APInt PtrOffset;
3895*9880d681SAndroid Build Coastguard Worker   if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
3896*9880d681SAndroid Build Coastguard Worker     return nullptr;
3897*9880d681SAndroid Build Coastguard Worker 
3898*9880d681SAndroid Build Coastguard Worker   Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
3899*9880d681SAndroid Build Coastguard Worker   Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
3900*9880d681SAndroid Build Coastguard Worker   Type *Int32PtrTy = Int32Ty->getPointerTo();
3901*9880d681SAndroid Build Coastguard Worker   Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
3902*9880d681SAndroid Build Coastguard Worker 
3903*9880d681SAndroid Build Coastguard Worker   auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
3904*9880d681SAndroid Build Coastguard Worker   if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
3905*9880d681SAndroid Build Coastguard Worker     return nullptr;
3906*9880d681SAndroid Build Coastguard Worker 
3907*9880d681SAndroid Build Coastguard Worker   uint64_t OffsetInt = OffsetConstInt->getSExtValue();
3908*9880d681SAndroid Build Coastguard Worker   if (OffsetInt % 4 != 0)
3909*9880d681SAndroid Build Coastguard Worker     return nullptr;
3910*9880d681SAndroid Build Coastguard Worker 
3911*9880d681SAndroid Build Coastguard Worker   Constant *C = ConstantExpr::getGetElementPtr(
3912*9880d681SAndroid Build Coastguard Worker       Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
3913*9880d681SAndroid Build Coastguard Worker       ConstantInt::get(Int64Ty, OffsetInt / 4));
3914*9880d681SAndroid Build Coastguard Worker   Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
3915*9880d681SAndroid Build Coastguard Worker   if (!Loaded)
3916*9880d681SAndroid Build Coastguard Worker     return nullptr;
3917*9880d681SAndroid Build Coastguard Worker 
3918*9880d681SAndroid Build Coastguard Worker   auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
3919*9880d681SAndroid Build Coastguard Worker   if (!LoadedCE)
3920*9880d681SAndroid Build Coastguard Worker     return nullptr;
3921*9880d681SAndroid Build Coastguard Worker 
3922*9880d681SAndroid Build Coastguard Worker   if (LoadedCE->getOpcode() == Instruction::Trunc) {
3923*9880d681SAndroid Build Coastguard Worker     LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
3924*9880d681SAndroid Build Coastguard Worker     if (!LoadedCE)
3925*9880d681SAndroid Build Coastguard Worker       return nullptr;
3926*9880d681SAndroid Build Coastguard Worker   }
3927*9880d681SAndroid Build Coastguard Worker 
3928*9880d681SAndroid Build Coastguard Worker   if (LoadedCE->getOpcode() != Instruction::Sub)
3929*9880d681SAndroid Build Coastguard Worker     return nullptr;
3930*9880d681SAndroid Build Coastguard Worker 
3931*9880d681SAndroid Build Coastguard Worker   auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
3932*9880d681SAndroid Build Coastguard Worker   if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
3933*9880d681SAndroid Build Coastguard Worker     return nullptr;
3934*9880d681SAndroid Build Coastguard Worker   auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
3935*9880d681SAndroid Build Coastguard Worker 
3936*9880d681SAndroid Build Coastguard Worker   Constant *LoadedRHS = LoadedCE->getOperand(1);
3937*9880d681SAndroid Build Coastguard Worker   GlobalValue *LoadedRHSSym;
3938*9880d681SAndroid Build Coastguard Worker   APInt LoadedRHSOffset;
3939*9880d681SAndroid Build Coastguard Worker   if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
3940*9880d681SAndroid Build Coastguard Worker                                   DL) ||
3941*9880d681SAndroid Build Coastguard Worker       PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
3942*9880d681SAndroid Build Coastguard Worker     return nullptr;
3943*9880d681SAndroid Build Coastguard Worker 
3944*9880d681SAndroid Build Coastguard Worker   return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
3945*9880d681SAndroid Build Coastguard Worker }
3946*9880d681SAndroid Build Coastguard Worker 
maskIsAllZeroOrUndef(Value * Mask)3947*9880d681SAndroid Build Coastguard Worker static bool maskIsAllZeroOrUndef(Value *Mask) {
3948*9880d681SAndroid Build Coastguard Worker   auto *ConstMask = dyn_cast<Constant>(Mask);
3949*9880d681SAndroid Build Coastguard Worker   if (!ConstMask)
3950*9880d681SAndroid Build Coastguard Worker     return false;
3951*9880d681SAndroid Build Coastguard Worker   if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
3952*9880d681SAndroid Build Coastguard Worker     return true;
3953*9880d681SAndroid Build Coastguard Worker   for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
3954*9880d681SAndroid Build Coastguard Worker        ++I) {
3955*9880d681SAndroid Build Coastguard Worker     if (auto *MaskElt = ConstMask->getAggregateElement(I))
3956*9880d681SAndroid Build Coastguard Worker       if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
3957*9880d681SAndroid Build Coastguard Worker         continue;
3958*9880d681SAndroid Build Coastguard Worker     return false;
3959*9880d681SAndroid Build Coastguard Worker   }
3960*9880d681SAndroid Build Coastguard Worker   return true;
3961*9880d681SAndroid Build Coastguard Worker }
3962*9880d681SAndroid Build Coastguard Worker 
3963*9880d681SAndroid Build Coastguard Worker template <typename IterTy>
SimplifyIntrinsic(Function * F,IterTy ArgBegin,IterTy ArgEnd,const Query & Q,unsigned MaxRecurse)3964*9880d681SAndroid Build Coastguard Worker static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
3965*9880d681SAndroid Build Coastguard Worker                                 const Query &Q, unsigned MaxRecurse) {
3966*9880d681SAndroid Build Coastguard Worker   Intrinsic::ID IID = F->getIntrinsicID();
3967*9880d681SAndroid Build Coastguard Worker   unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
3968*9880d681SAndroid Build Coastguard Worker   Type *ReturnType = F->getReturnType();
3969*9880d681SAndroid Build Coastguard Worker 
3970*9880d681SAndroid Build Coastguard Worker   // Binary Ops
3971*9880d681SAndroid Build Coastguard Worker   if (NumOperands == 2) {
3972*9880d681SAndroid Build Coastguard Worker     Value *LHS = *ArgBegin;
3973*9880d681SAndroid Build Coastguard Worker     Value *RHS = *(ArgBegin + 1);
3974*9880d681SAndroid Build Coastguard Worker     if (IID == Intrinsic::usub_with_overflow ||
3975*9880d681SAndroid Build Coastguard Worker         IID == Intrinsic::ssub_with_overflow) {
3976*9880d681SAndroid Build Coastguard Worker       // X - X -> { 0, false }
3977*9880d681SAndroid Build Coastguard Worker       if (LHS == RHS)
3978*9880d681SAndroid Build Coastguard Worker         return Constant::getNullValue(ReturnType);
3979*9880d681SAndroid Build Coastguard Worker 
3980*9880d681SAndroid Build Coastguard Worker       // X - undef -> undef
3981*9880d681SAndroid Build Coastguard Worker       // undef - X -> undef
3982*9880d681SAndroid Build Coastguard Worker       if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
3983*9880d681SAndroid Build Coastguard Worker         return UndefValue::get(ReturnType);
3984*9880d681SAndroid Build Coastguard Worker     }
3985*9880d681SAndroid Build Coastguard Worker 
3986*9880d681SAndroid Build Coastguard Worker     if (IID == Intrinsic::uadd_with_overflow ||
3987*9880d681SAndroid Build Coastguard Worker         IID == Intrinsic::sadd_with_overflow) {
3988*9880d681SAndroid Build Coastguard Worker       // X + undef -> undef
3989*9880d681SAndroid Build Coastguard Worker       if (isa<UndefValue>(RHS))
3990*9880d681SAndroid Build Coastguard Worker         return UndefValue::get(ReturnType);
3991*9880d681SAndroid Build Coastguard Worker     }
3992*9880d681SAndroid Build Coastguard Worker 
3993*9880d681SAndroid Build Coastguard Worker     if (IID == Intrinsic::umul_with_overflow ||
3994*9880d681SAndroid Build Coastguard Worker         IID == Intrinsic::smul_with_overflow) {
3995*9880d681SAndroid Build Coastguard Worker       // X * 0 -> { 0, false }
3996*9880d681SAndroid Build Coastguard Worker       if (match(RHS, m_Zero()))
3997*9880d681SAndroid Build Coastguard Worker         return Constant::getNullValue(ReturnType);
3998*9880d681SAndroid Build Coastguard Worker 
3999*9880d681SAndroid Build Coastguard Worker       // X * undef -> { 0, false }
4000*9880d681SAndroid Build Coastguard Worker       if (match(RHS, m_Undef()))
4001*9880d681SAndroid Build Coastguard Worker         return Constant::getNullValue(ReturnType);
4002*9880d681SAndroid Build Coastguard Worker     }
4003*9880d681SAndroid Build Coastguard Worker 
4004*9880d681SAndroid Build Coastguard Worker     if (IID == Intrinsic::load_relative && isa<Constant>(LHS) &&
4005*9880d681SAndroid Build Coastguard Worker         isa<Constant>(RHS))
4006*9880d681SAndroid Build Coastguard Worker       return SimplifyRelativeLoad(cast<Constant>(LHS), cast<Constant>(RHS),
4007*9880d681SAndroid Build Coastguard Worker                                   Q.DL);
4008*9880d681SAndroid Build Coastguard Worker   }
4009*9880d681SAndroid Build Coastguard Worker 
4010*9880d681SAndroid Build Coastguard Worker   // Simplify calls to llvm.masked.load.*
4011*9880d681SAndroid Build Coastguard Worker   if (IID == Intrinsic::masked_load) {
4012*9880d681SAndroid Build Coastguard Worker     Value *MaskArg = ArgBegin[2];
4013*9880d681SAndroid Build Coastguard Worker     Value *PassthruArg = ArgBegin[3];
4014*9880d681SAndroid Build Coastguard Worker     // If the mask is all zeros or undef, the "passthru" argument is the result.
4015*9880d681SAndroid Build Coastguard Worker     if (maskIsAllZeroOrUndef(MaskArg))
4016*9880d681SAndroid Build Coastguard Worker       return PassthruArg;
4017*9880d681SAndroid Build Coastguard Worker   }
4018*9880d681SAndroid Build Coastguard Worker 
4019*9880d681SAndroid Build Coastguard Worker   // Perform idempotent optimizations
4020*9880d681SAndroid Build Coastguard Worker   if (!IsIdempotent(IID))
4021*9880d681SAndroid Build Coastguard Worker     return nullptr;
4022*9880d681SAndroid Build Coastguard Worker 
4023*9880d681SAndroid Build Coastguard Worker   // Unary Ops
4024*9880d681SAndroid Build Coastguard Worker   if (NumOperands == 1)
4025*9880d681SAndroid Build Coastguard Worker     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
4026*9880d681SAndroid Build Coastguard Worker       if (II->getIntrinsicID() == IID)
4027*9880d681SAndroid Build Coastguard Worker         return II;
4028*9880d681SAndroid Build Coastguard Worker 
4029*9880d681SAndroid Build Coastguard Worker   return nullptr;
4030*9880d681SAndroid Build Coastguard Worker }
4031*9880d681SAndroid Build Coastguard Worker 
4032*9880d681SAndroid Build Coastguard Worker template <typename IterTy>
SimplifyCall(Value * V,IterTy ArgBegin,IterTy ArgEnd,const Query & Q,unsigned MaxRecurse)4033*9880d681SAndroid Build Coastguard Worker static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
4034*9880d681SAndroid Build Coastguard Worker                            const Query &Q, unsigned MaxRecurse) {
4035*9880d681SAndroid Build Coastguard Worker   Type *Ty = V->getType();
4036*9880d681SAndroid Build Coastguard Worker   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
4037*9880d681SAndroid Build Coastguard Worker     Ty = PTy->getElementType();
4038*9880d681SAndroid Build Coastguard Worker   FunctionType *FTy = cast<FunctionType>(Ty);
4039*9880d681SAndroid Build Coastguard Worker 
4040*9880d681SAndroid Build Coastguard Worker   // call undef -> undef
4041*9880d681SAndroid Build Coastguard Worker   // call null -> undef
4042*9880d681SAndroid Build Coastguard Worker   if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
4043*9880d681SAndroid Build Coastguard Worker     return UndefValue::get(FTy->getReturnType());
4044*9880d681SAndroid Build Coastguard Worker 
4045*9880d681SAndroid Build Coastguard Worker   Function *F = dyn_cast<Function>(V);
4046*9880d681SAndroid Build Coastguard Worker   if (!F)
4047*9880d681SAndroid Build Coastguard Worker     return nullptr;
4048*9880d681SAndroid Build Coastguard Worker 
4049*9880d681SAndroid Build Coastguard Worker   if (F->isIntrinsic())
4050*9880d681SAndroid Build Coastguard Worker     if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
4051*9880d681SAndroid Build Coastguard Worker       return Ret;
4052*9880d681SAndroid Build Coastguard Worker 
4053*9880d681SAndroid Build Coastguard Worker   if (!canConstantFoldCallTo(F))
4054*9880d681SAndroid Build Coastguard Worker     return nullptr;
4055*9880d681SAndroid Build Coastguard Worker 
4056*9880d681SAndroid Build Coastguard Worker   SmallVector<Constant *, 4> ConstantArgs;
4057*9880d681SAndroid Build Coastguard Worker   ConstantArgs.reserve(ArgEnd - ArgBegin);
4058*9880d681SAndroid Build Coastguard Worker   for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
4059*9880d681SAndroid Build Coastguard Worker     Constant *C = dyn_cast<Constant>(*I);
4060*9880d681SAndroid Build Coastguard Worker     if (!C)
4061*9880d681SAndroid Build Coastguard Worker       return nullptr;
4062*9880d681SAndroid Build Coastguard Worker     ConstantArgs.push_back(C);
4063*9880d681SAndroid Build Coastguard Worker   }
4064*9880d681SAndroid Build Coastguard Worker 
4065*9880d681SAndroid Build Coastguard Worker   return ConstantFoldCall(F, ConstantArgs, Q.TLI);
4066*9880d681SAndroid Build Coastguard Worker }
4067*9880d681SAndroid Build Coastguard Worker 
SimplifyCall(Value * V,User::op_iterator ArgBegin,User::op_iterator ArgEnd,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)4068*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
4069*9880d681SAndroid Build Coastguard Worker                           User::op_iterator ArgEnd, const DataLayout &DL,
4070*9880d681SAndroid Build Coastguard Worker                           const TargetLibraryInfo *TLI, const DominatorTree *DT,
4071*9880d681SAndroid Build Coastguard Worker                           AssumptionCache *AC, const Instruction *CxtI) {
4072*9880d681SAndroid Build Coastguard Worker   return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AC, CxtI),
4073*9880d681SAndroid Build Coastguard Worker                         RecursionLimit);
4074*9880d681SAndroid Build Coastguard Worker }
4075*9880d681SAndroid Build Coastguard Worker 
SimplifyCall(Value * V,ArrayRef<Value * > Args,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC,const Instruction * CxtI)4076*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
4077*9880d681SAndroid Build Coastguard Worker                           const DataLayout &DL, const TargetLibraryInfo *TLI,
4078*9880d681SAndroid Build Coastguard Worker                           const DominatorTree *DT, AssumptionCache *AC,
4079*9880d681SAndroid Build Coastguard Worker                           const Instruction *CxtI) {
4080*9880d681SAndroid Build Coastguard Worker   return ::SimplifyCall(V, Args.begin(), Args.end(),
4081*9880d681SAndroid Build Coastguard Worker                         Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
4082*9880d681SAndroid Build Coastguard Worker }
4083*9880d681SAndroid Build Coastguard Worker 
4084*9880d681SAndroid Build Coastguard Worker /// See if we can compute a simplified version of this instruction.
4085*9880d681SAndroid Build Coastguard Worker /// If not, this returns null.
SimplifyInstruction(Instruction * I,const DataLayout & DL,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC)4086*9880d681SAndroid Build Coastguard Worker Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
4087*9880d681SAndroid Build Coastguard Worker                                  const TargetLibraryInfo *TLI,
4088*9880d681SAndroid Build Coastguard Worker                                  const DominatorTree *DT, AssumptionCache *AC) {
4089*9880d681SAndroid Build Coastguard Worker   Value *Result;
4090*9880d681SAndroid Build Coastguard Worker 
4091*9880d681SAndroid Build Coastguard Worker   switch (I->getOpcode()) {
4092*9880d681SAndroid Build Coastguard Worker   default:
4093*9880d681SAndroid Build Coastguard Worker     Result = ConstantFoldInstruction(I, DL, TLI);
4094*9880d681SAndroid Build Coastguard Worker     break;
4095*9880d681SAndroid Build Coastguard Worker   case Instruction::FAdd:
4096*9880d681SAndroid Build Coastguard Worker     Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
4097*9880d681SAndroid Build Coastguard Worker                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4098*9880d681SAndroid Build Coastguard Worker     break;
4099*9880d681SAndroid Build Coastguard Worker   case Instruction::Add:
4100*9880d681SAndroid Build Coastguard Worker     Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
4101*9880d681SAndroid Build Coastguard Worker                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
4102*9880d681SAndroid Build Coastguard Worker                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4103*9880d681SAndroid Build Coastguard Worker                              TLI, DT, AC, I);
4104*9880d681SAndroid Build Coastguard Worker     break;
4105*9880d681SAndroid Build Coastguard Worker   case Instruction::FSub:
4106*9880d681SAndroid Build Coastguard Worker     Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
4107*9880d681SAndroid Build Coastguard Worker                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4108*9880d681SAndroid Build Coastguard Worker     break;
4109*9880d681SAndroid Build Coastguard Worker   case Instruction::Sub:
4110*9880d681SAndroid Build Coastguard Worker     Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
4111*9880d681SAndroid Build Coastguard Worker                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
4112*9880d681SAndroid Build Coastguard Worker                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4113*9880d681SAndroid Build Coastguard Worker                              TLI, DT, AC, I);
4114*9880d681SAndroid Build Coastguard Worker     break;
4115*9880d681SAndroid Build Coastguard Worker   case Instruction::FMul:
4116*9880d681SAndroid Build Coastguard Worker     Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
4117*9880d681SAndroid Build Coastguard Worker                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4118*9880d681SAndroid Build Coastguard Worker     break;
4119*9880d681SAndroid Build Coastguard Worker   case Instruction::Mul:
4120*9880d681SAndroid Build Coastguard Worker     Result =
4121*9880d681SAndroid Build Coastguard Worker         SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
4122*9880d681SAndroid Build Coastguard Worker     break;
4123*9880d681SAndroid Build Coastguard Worker   case Instruction::SDiv:
4124*9880d681SAndroid Build Coastguard Worker     Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4125*9880d681SAndroid Build Coastguard Worker                               AC, I);
4126*9880d681SAndroid Build Coastguard Worker     break;
4127*9880d681SAndroid Build Coastguard Worker   case Instruction::UDiv:
4128*9880d681SAndroid Build Coastguard Worker     Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4129*9880d681SAndroid Build Coastguard Worker                               AC, I);
4130*9880d681SAndroid Build Coastguard Worker     break;
4131*9880d681SAndroid Build Coastguard Worker   case Instruction::FDiv:
4132*9880d681SAndroid Build Coastguard Worker     Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
4133*9880d681SAndroid Build Coastguard Worker                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4134*9880d681SAndroid Build Coastguard Worker     break;
4135*9880d681SAndroid Build Coastguard Worker   case Instruction::SRem:
4136*9880d681SAndroid Build Coastguard Worker     Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4137*9880d681SAndroid Build Coastguard Worker                               AC, I);
4138*9880d681SAndroid Build Coastguard Worker     break;
4139*9880d681SAndroid Build Coastguard Worker   case Instruction::URem:
4140*9880d681SAndroid Build Coastguard Worker     Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4141*9880d681SAndroid Build Coastguard Worker                               AC, I);
4142*9880d681SAndroid Build Coastguard Worker     break;
4143*9880d681SAndroid Build Coastguard Worker   case Instruction::FRem:
4144*9880d681SAndroid Build Coastguard Worker     Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
4145*9880d681SAndroid Build Coastguard Worker                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4146*9880d681SAndroid Build Coastguard Worker     break;
4147*9880d681SAndroid Build Coastguard Worker   case Instruction::Shl:
4148*9880d681SAndroid Build Coastguard Worker     Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
4149*9880d681SAndroid Build Coastguard Worker                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
4150*9880d681SAndroid Build Coastguard Worker                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4151*9880d681SAndroid Build Coastguard Worker                              TLI, DT, AC, I);
4152*9880d681SAndroid Build Coastguard Worker     break;
4153*9880d681SAndroid Build Coastguard Worker   case Instruction::LShr:
4154*9880d681SAndroid Build Coastguard Worker     Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
4155*9880d681SAndroid Build Coastguard Worker                               cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
4156*9880d681SAndroid Build Coastguard Worker                               AC, I);
4157*9880d681SAndroid Build Coastguard Worker     break;
4158*9880d681SAndroid Build Coastguard Worker   case Instruction::AShr:
4159*9880d681SAndroid Build Coastguard Worker     Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
4160*9880d681SAndroid Build Coastguard Worker                               cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
4161*9880d681SAndroid Build Coastguard Worker                               AC, I);
4162*9880d681SAndroid Build Coastguard Worker     break;
4163*9880d681SAndroid Build Coastguard Worker   case Instruction::And:
4164*9880d681SAndroid Build Coastguard Worker     Result =
4165*9880d681SAndroid Build Coastguard Worker         SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
4166*9880d681SAndroid Build Coastguard Worker     break;
4167*9880d681SAndroid Build Coastguard Worker   case Instruction::Or:
4168*9880d681SAndroid Build Coastguard Worker     Result =
4169*9880d681SAndroid Build Coastguard Worker         SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
4170*9880d681SAndroid Build Coastguard Worker     break;
4171*9880d681SAndroid Build Coastguard Worker   case Instruction::Xor:
4172*9880d681SAndroid Build Coastguard Worker     Result =
4173*9880d681SAndroid Build Coastguard Worker         SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
4174*9880d681SAndroid Build Coastguard Worker     break;
4175*9880d681SAndroid Build Coastguard Worker   case Instruction::ICmp:
4176*9880d681SAndroid Build Coastguard Worker     Result =
4177*9880d681SAndroid Build Coastguard Worker         SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), I->getOperand(0),
4178*9880d681SAndroid Build Coastguard Worker                          I->getOperand(1), DL, TLI, DT, AC, I);
4179*9880d681SAndroid Build Coastguard Worker     break;
4180*9880d681SAndroid Build Coastguard Worker   case Instruction::FCmp:
4181*9880d681SAndroid Build Coastguard Worker     Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
4182*9880d681SAndroid Build Coastguard Worker                               I->getOperand(0), I->getOperand(1),
4183*9880d681SAndroid Build Coastguard Worker                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
4184*9880d681SAndroid Build Coastguard Worker     break;
4185*9880d681SAndroid Build Coastguard Worker   case Instruction::Select:
4186*9880d681SAndroid Build Coastguard Worker     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
4187*9880d681SAndroid Build Coastguard Worker                                 I->getOperand(2), DL, TLI, DT, AC, I);
4188*9880d681SAndroid Build Coastguard Worker     break;
4189*9880d681SAndroid Build Coastguard Worker   case Instruction::GetElementPtr: {
4190*9880d681SAndroid Build Coastguard Worker     SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
4191*9880d681SAndroid Build Coastguard Worker     Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
4192*9880d681SAndroid Build Coastguard Worker                              Ops, DL, TLI, DT, AC, I);
4193*9880d681SAndroid Build Coastguard Worker     break;
4194*9880d681SAndroid Build Coastguard Worker   }
4195*9880d681SAndroid Build Coastguard Worker   case Instruction::InsertValue: {
4196*9880d681SAndroid Build Coastguard Worker     InsertValueInst *IV = cast<InsertValueInst>(I);
4197*9880d681SAndroid Build Coastguard Worker     Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
4198*9880d681SAndroid Build Coastguard Worker                                      IV->getInsertedValueOperand(),
4199*9880d681SAndroid Build Coastguard Worker                                      IV->getIndices(), DL, TLI, DT, AC, I);
4200*9880d681SAndroid Build Coastguard Worker     break;
4201*9880d681SAndroid Build Coastguard Worker   }
4202*9880d681SAndroid Build Coastguard Worker   case Instruction::ExtractValue: {
4203*9880d681SAndroid Build Coastguard Worker     auto *EVI = cast<ExtractValueInst>(I);
4204*9880d681SAndroid Build Coastguard Worker     Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
4205*9880d681SAndroid Build Coastguard Worker                                       EVI->getIndices(), DL, TLI, DT, AC, I);
4206*9880d681SAndroid Build Coastguard Worker     break;
4207*9880d681SAndroid Build Coastguard Worker   }
4208*9880d681SAndroid Build Coastguard Worker   case Instruction::ExtractElement: {
4209*9880d681SAndroid Build Coastguard Worker     auto *EEI = cast<ExtractElementInst>(I);
4210*9880d681SAndroid Build Coastguard Worker     Result = SimplifyExtractElementInst(
4211*9880d681SAndroid Build Coastguard Worker         EEI->getVectorOperand(), EEI->getIndexOperand(), DL, TLI, DT, AC, I);
4212*9880d681SAndroid Build Coastguard Worker     break;
4213*9880d681SAndroid Build Coastguard Worker   }
4214*9880d681SAndroid Build Coastguard Worker   case Instruction::PHI:
4215*9880d681SAndroid Build Coastguard Worker     Result = SimplifyPHINode(cast<PHINode>(I), Query(DL, TLI, DT, AC, I));
4216*9880d681SAndroid Build Coastguard Worker     break;
4217*9880d681SAndroid Build Coastguard Worker   case Instruction::Call: {
4218*9880d681SAndroid Build Coastguard Worker     CallSite CS(cast<CallInst>(I));
4219*9880d681SAndroid Build Coastguard Worker     Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), DL,
4220*9880d681SAndroid Build Coastguard Worker                           TLI, DT, AC, I);
4221*9880d681SAndroid Build Coastguard Worker     break;
4222*9880d681SAndroid Build Coastguard Worker   }
4223*9880d681SAndroid Build Coastguard Worker   case Instruction::Trunc:
4224*9880d681SAndroid Build Coastguard Worker     Result =
4225*9880d681SAndroid Build Coastguard Worker         SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT, AC, I);
4226*9880d681SAndroid Build Coastguard Worker     break;
4227*9880d681SAndroid Build Coastguard Worker   }
4228*9880d681SAndroid Build Coastguard Worker 
4229*9880d681SAndroid Build Coastguard Worker   // In general, it is possible for computeKnownBits to determine all bits in a
4230*9880d681SAndroid Build Coastguard Worker   // value even when the operands are not all constants.
4231*9880d681SAndroid Build Coastguard Worker   if (!Result && I->getType()->isIntegerTy()) {
4232*9880d681SAndroid Build Coastguard Worker     unsigned BitWidth = I->getType()->getScalarSizeInBits();
4233*9880d681SAndroid Build Coastguard Worker     APInt KnownZero(BitWidth, 0);
4234*9880d681SAndroid Build Coastguard Worker     APInt KnownOne(BitWidth, 0);
4235*9880d681SAndroid Build Coastguard Worker     computeKnownBits(I, KnownZero, KnownOne, DL, /*Depth*/0, AC, I, DT);
4236*9880d681SAndroid Build Coastguard Worker     if ((KnownZero | KnownOne).isAllOnesValue())
4237*9880d681SAndroid Build Coastguard Worker       Result = ConstantInt::get(I->getContext(), KnownOne);
4238*9880d681SAndroid Build Coastguard Worker   }
4239*9880d681SAndroid Build Coastguard Worker 
4240*9880d681SAndroid Build Coastguard Worker   /// If called on unreachable code, the above logic may report that the
4241*9880d681SAndroid Build Coastguard Worker   /// instruction simplified to itself.  Make life easier for users by
4242*9880d681SAndroid Build Coastguard Worker   /// detecting that case here, returning a safe value instead.
4243*9880d681SAndroid Build Coastguard Worker   return Result == I ? UndefValue::get(I->getType()) : Result;
4244*9880d681SAndroid Build Coastguard Worker }
4245*9880d681SAndroid Build Coastguard Worker 
4246*9880d681SAndroid Build Coastguard Worker /// \brief Implementation of recursive simplification through an instruction's
4247*9880d681SAndroid Build Coastguard Worker /// uses.
4248*9880d681SAndroid Build Coastguard Worker ///
4249*9880d681SAndroid Build Coastguard Worker /// This is the common implementation of the recursive simplification routines.
4250*9880d681SAndroid Build Coastguard Worker /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
4251*9880d681SAndroid Build Coastguard Worker /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
4252*9880d681SAndroid Build Coastguard Worker /// instructions to process and attempt to simplify it using
4253*9880d681SAndroid Build Coastguard Worker /// InstructionSimplify.
4254*9880d681SAndroid Build Coastguard Worker ///
4255*9880d681SAndroid Build Coastguard Worker /// This routine returns 'true' only when *it* simplifies something. The passed
4256*9880d681SAndroid Build Coastguard Worker /// in simplified value does not count toward this.
replaceAndRecursivelySimplifyImpl(Instruction * I,Value * SimpleV,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC)4257*9880d681SAndroid Build Coastguard Worker static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
4258*9880d681SAndroid Build Coastguard Worker                                               const TargetLibraryInfo *TLI,
4259*9880d681SAndroid Build Coastguard Worker                                               const DominatorTree *DT,
4260*9880d681SAndroid Build Coastguard Worker                                               AssumptionCache *AC) {
4261*9880d681SAndroid Build Coastguard Worker   bool Simplified = false;
4262*9880d681SAndroid Build Coastguard Worker   SmallSetVector<Instruction *, 8> Worklist;
4263*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = I->getModule()->getDataLayout();
4264*9880d681SAndroid Build Coastguard Worker 
4265*9880d681SAndroid Build Coastguard Worker   // If we have an explicit value to collapse to, do that round of the
4266*9880d681SAndroid Build Coastguard Worker   // simplification loop by hand initially.
4267*9880d681SAndroid Build Coastguard Worker   if (SimpleV) {
4268*9880d681SAndroid Build Coastguard Worker     for (User *U : I->users())
4269*9880d681SAndroid Build Coastguard Worker       if (U != I)
4270*9880d681SAndroid Build Coastguard Worker         Worklist.insert(cast<Instruction>(U));
4271*9880d681SAndroid Build Coastguard Worker 
4272*9880d681SAndroid Build Coastguard Worker     // Replace the instruction with its simplified value.
4273*9880d681SAndroid Build Coastguard Worker     I->replaceAllUsesWith(SimpleV);
4274*9880d681SAndroid Build Coastguard Worker 
4275*9880d681SAndroid Build Coastguard Worker     // Gracefully handle edge cases where the instruction is not wired into any
4276*9880d681SAndroid Build Coastguard Worker     // parent block.
4277*9880d681SAndroid Build Coastguard Worker     if (I->getParent())
4278*9880d681SAndroid Build Coastguard Worker       I->eraseFromParent();
4279*9880d681SAndroid Build Coastguard Worker   } else {
4280*9880d681SAndroid Build Coastguard Worker     Worklist.insert(I);
4281*9880d681SAndroid Build Coastguard Worker   }
4282*9880d681SAndroid Build Coastguard Worker 
4283*9880d681SAndroid Build Coastguard Worker   // Note that we must test the size on each iteration, the worklist can grow.
4284*9880d681SAndroid Build Coastguard Worker   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
4285*9880d681SAndroid Build Coastguard Worker     I = Worklist[Idx];
4286*9880d681SAndroid Build Coastguard Worker 
4287*9880d681SAndroid Build Coastguard Worker     // See if this instruction simplifies.
4288*9880d681SAndroid Build Coastguard Worker     SimpleV = SimplifyInstruction(I, DL, TLI, DT, AC);
4289*9880d681SAndroid Build Coastguard Worker     if (!SimpleV)
4290*9880d681SAndroid Build Coastguard Worker       continue;
4291*9880d681SAndroid Build Coastguard Worker 
4292*9880d681SAndroid Build Coastguard Worker     Simplified = true;
4293*9880d681SAndroid Build Coastguard Worker 
4294*9880d681SAndroid Build Coastguard Worker     // Stash away all the uses of the old instruction so we can check them for
4295*9880d681SAndroid Build Coastguard Worker     // recursive simplifications after a RAUW. This is cheaper than checking all
4296*9880d681SAndroid Build Coastguard Worker     // uses of To on the recursive step in most cases.
4297*9880d681SAndroid Build Coastguard Worker     for (User *U : I->users())
4298*9880d681SAndroid Build Coastguard Worker       Worklist.insert(cast<Instruction>(U));
4299*9880d681SAndroid Build Coastguard Worker 
4300*9880d681SAndroid Build Coastguard Worker     // Replace the instruction with its simplified value.
4301*9880d681SAndroid Build Coastguard Worker     I->replaceAllUsesWith(SimpleV);
4302*9880d681SAndroid Build Coastguard Worker 
4303*9880d681SAndroid Build Coastguard Worker     // Gracefully handle edge cases where the instruction is not wired into any
4304*9880d681SAndroid Build Coastguard Worker     // parent block.
4305*9880d681SAndroid Build Coastguard Worker     if (I->getParent())
4306*9880d681SAndroid Build Coastguard Worker       I->eraseFromParent();
4307*9880d681SAndroid Build Coastguard Worker   }
4308*9880d681SAndroid Build Coastguard Worker   return Simplified;
4309*9880d681SAndroid Build Coastguard Worker }
4310*9880d681SAndroid Build Coastguard Worker 
recursivelySimplifyInstruction(Instruction * I,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC)4311*9880d681SAndroid Build Coastguard Worker bool llvm::recursivelySimplifyInstruction(Instruction *I,
4312*9880d681SAndroid Build Coastguard Worker                                           const TargetLibraryInfo *TLI,
4313*9880d681SAndroid Build Coastguard Worker                                           const DominatorTree *DT,
4314*9880d681SAndroid Build Coastguard Worker                                           AssumptionCache *AC) {
4315*9880d681SAndroid Build Coastguard Worker   return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
4316*9880d681SAndroid Build Coastguard Worker }
4317*9880d681SAndroid Build Coastguard Worker 
replaceAndRecursivelySimplify(Instruction * I,Value * SimpleV,const TargetLibraryInfo * TLI,const DominatorTree * DT,AssumptionCache * AC)4318*9880d681SAndroid Build Coastguard Worker bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
4319*9880d681SAndroid Build Coastguard Worker                                          const TargetLibraryInfo *TLI,
4320*9880d681SAndroid Build Coastguard Worker                                          const DominatorTree *DT,
4321*9880d681SAndroid Build Coastguard Worker                                          AssumptionCache *AC) {
4322*9880d681SAndroid Build Coastguard Worker   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
4323*9880d681SAndroid Build Coastguard Worker   assert(SimpleV && "Must provide a simplified value.");
4324*9880d681SAndroid Build Coastguard Worker   return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
4325*9880d681SAndroid Build Coastguard Worker }
4326