blob: 1699a0ce89cd1985b373e2fd8e6998413cbac898 [file] [log] [blame]
Chris Lattner0a8191e2010-01-05 07:50:36 +00001//===- InstCombineAndOrXor.cpp --------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitAnd, visitOr, and visitXor functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000015#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000016#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/Intrinsics.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000018#include "llvm/IR/PatternMatch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Transforms/Utils/CmpInstAnalysis.h"
James Molloyf01488e2016-01-15 09:20:19 +000020#include "llvm/Transforms/Utils/Local.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000021using namespace llvm;
22using namespace PatternMatch;
23
Chandler Carruth964daaa2014-04-22 02:55:47 +000024#define DEBUG_TYPE "instcombine"
25
Sanjay Patel18549272015-09-08 18:24:36 +000026/// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
Tim Shenaec68b22016-06-29 20:10:17 +000027/// a four bit mask.
28static unsigned getFCmpCode(FCmpInst::Predicate CC) {
29 assert(FCmpInst::FCMP_FALSE <= CC && CC <= FCmpInst::FCMP_TRUE &&
30 "Unexpected FCmp predicate!");
31 // Take advantage of the bit pattern of FCmpInst::Predicate here.
32 // U L G E
33 static_assert(FCmpInst::FCMP_FALSE == 0, ""); // 0 0 0 0
34 static_assert(FCmpInst::FCMP_OEQ == 1, ""); // 0 0 0 1
35 static_assert(FCmpInst::FCMP_OGT == 2, ""); // 0 0 1 0
36 static_assert(FCmpInst::FCMP_OGE == 3, ""); // 0 0 1 1
37 static_assert(FCmpInst::FCMP_OLT == 4, ""); // 0 1 0 0
38 static_assert(FCmpInst::FCMP_OLE == 5, ""); // 0 1 0 1
39 static_assert(FCmpInst::FCMP_ONE == 6, ""); // 0 1 1 0
40 static_assert(FCmpInst::FCMP_ORD == 7, ""); // 0 1 1 1
41 static_assert(FCmpInst::FCMP_UNO == 8, ""); // 1 0 0 0
42 static_assert(FCmpInst::FCMP_UEQ == 9, ""); // 1 0 0 1
43 static_assert(FCmpInst::FCMP_UGT == 10, ""); // 1 0 1 0
44 static_assert(FCmpInst::FCMP_UGE == 11, ""); // 1 0 1 1
45 static_assert(FCmpInst::FCMP_ULT == 12, ""); // 1 1 0 0
46 static_assert(FCmpInst::FCMP_ULE == 13, ""); // 1 1 0 1
47 static_assert(FCmpInst::FCMP_UNE == 14, ""); // 1 1 1 0
48 static_assert(FCmpInst::FCMP_TRUE == 15, ""); // 1 1 1 1
49 return CC;
Chris Lattner0a8191e2010-01-05 07:50:36 +000050}
51
Sanjay Patel18549272015-09-08 18:24:36 +000052/// This is the complement of getICmpCode, which turns an opcode and two
53/// operands into either a constant true or false, or a brand new ICmp
54/// instruction. The sign is passed in to determine which kind of predicate to
55/// use in the new icmp instruction.
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000056static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
Craig Topperbb4069e2017-07-07 23:16:26 +000057 InstCombiner::BuilderTy &Builder) {
Pete Cooperebf98c12011-12-17 01:20:32 +000058 ICmpInst::Predicate NewPred;
59 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
60 return NewConstant;
Craig Topperbb4069e2017-07-07 23:16:26 +000061 return Builder.CreateICmp(NewPred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000062}
63
Sanjay Patel18549272015-09-08 18:24:36 +000064/// This is the complement of getFCmpCode, which turns an opcode and two
Tim Shenaec68b22016-06-29 20:10:17 +000065/// operands into either a FCmp instruction, or a true/false constant.
66static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
Craig Topperbb4069e2017-07-07 23:16:26 +000067 InstCombiner::BuilderTy &Builder) {
Tim Shenaec68b22016-06-29 20:10:17 +000068 const auto Pred = static_cast<FCmpInst::Predicate>(Code);
69 assert(FCmpInst::FCMP_FALSE <= Pred && Pred <= FCmpInst::FCMP_TRUE &&
70 "Unexpected FCmp predicate!");
71 if (Pred == FCmpInst::FCMP_FALSE)
72 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
73 if (Pred == FCmpInst::FCMP_TRUE)
74 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Craig Topperbb4069e2017-07-07 23:16:26 +000075 return Builder.CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000076}
77
Craig Topperfc42ace2017-07-06 16:24:22 +000078/// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) or
79/// BITWISE_OP(BSWAP(A), Constant) to BSWAP(BITWISE_OP(A, B))
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000080/// \param I Binary operator to transform.
81/// \return Pointer to node that must replace the original binary operator, or
82/// null pointer if no transformation was made.
Craig Topper95e41422017-07-06 16:24:23 +000083static Value *SimplifyBSwap(BinaryOperator &I,
Craig Topperbb4069e2017-07-07 23:16:26 +000084 InstCombiner::BuilderTy &Builder) {
Craig Topperc6948c22017-07-03 05:54:11 +000085 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bswap simplifying");
86
Craig Topper22795de2017-07-06 16:24:21 +000087 Value *OldLHS = I.getOperand(0);
88 Value *OldRHS = I.getOperand(1);
Craig Topper80369702017-07-03 05:54:16 +000089
Craig Topper766ce6e2017-07-03 05:54:15 +000090 Value *NewLHS;
Craig Topper22795de2017-07-06 16:24:21 +000091 if (!match(OldLHS, m_BSwap(m_Value(NewLHS))))
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000092 return nullptr;
93
Craig Topper766ce6e2017-07-03 05:54:15 +000094 Value *NewRHS;
95 const APInt *C;
96
Craig Topper22795de2017-07-06 16:24:21 +000097 if (match(OldRHS, m_BSwap(m_Value(NewRHS)))) {
Craig Topper766ce6e2017-07-03 05:54:15 +000098 // OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
Craig Topper22795de2017-07-06 16:24:21 +000099 if (!OldLHS->hasOneUse() && !OldRHS->hasOneUse())
100 return nullptr;
Craig Topper766ce6e2017-07-03 05:54:15 +0000101 // NewRHS initialized by the matcher.
Craig Topper22795de2017-07-06 16:24:21 +0000102 } else if (match(OldRHS, m_APInt(C))) {
Craig Topper766ce6e2017-07-03 05:54:15 +0000103 // OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
Craig Topper22795de2017-07-06 16:24:21 +0000104 if (!OldLHS->hasOneUse())
105 return nullptr;
Craig Topper766ce6e2017-07-03 05:54:15 +0000106 NewRHS = ConstantInt::get(I.getType(), C->byteSwap());
107 } else
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000108 return nullptr;
109
Craig Topperbb4069e2017-07-07 23:16:26 +0000110 Value *BinOp = Builder.CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
Craig Topper1e4643a2017-07-03 05:54:13 +0000111 Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap,
112 I.getType());
Craig Topperbb4069e2017-07-07 23:16:26 +0000113 return Builder.CreateCall(F, BinOp);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000114}
115
Sanjay Patel18549272015-09-08 18:24:36 +0000116/// This handles expressions of the form ((val OP C1) & C2). Where
Craig Topper70e4f432017-04-02 17:57:30 +0000117/// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.
118Instruction *InstCombiner::OptAndOp(BinaryOperator *Op,
Chris Lattner0a8191e2010-01-05 07:50:36 +0000119 ConstantInt *OpRHS,
120 ConstantInt *AndRHS,
121 BinaryOperator &TheAnd) {
122 Value *X = Op->getOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +0000123 Constant *Together = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000124 if (!Op->isShift())
125 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
126
127 switch (Op->getOpcode()) {
Craig Topper70e4f432017-04-02 17:57:30 +0000128 default: break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000129 case Instruction::Or:
Owen Andersonc237a842010-09-13 17:59:27 +0000130 if (Op->hasOneUse()){
Owen Andersonc237a842010-09-13 17:59:27 +0000131 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
132 if (TogetherCI && !TogetherCI->isZero()){
133 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
134 // NOTE: This reduces the number of bits set in the & mask, which
135 // can expose opportunities for store narrowing.
136 Together = ConstantExpr::getXor(AndRHS, Together);
Craig Topperbb4069e2017-07-07 23:16:26 +0000137 Value *And = Builder.CreateAnd(X, Together);
Owen Andersonc237a842010-09-13 17:59:27 +0000138 And->takeName(Op);
139 return BinaryOperator::CreateOr(And, OpRHS);
140 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000141 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000142
Chris Lattner0a8191e2010-01-05 07:50:36 +0000143 break;
144 case Instruction::Add:
145 if (Op->hasOneUse()) {
146 // Adding a one to a single bit bit-field should be turned into an XOR
147 // of the bit. First thing to check is to see if this AND is with a
148 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000149 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000150
151 // If there is only one bit set.
152 if (AndRHSV.isPowerOf2()) {
153 // Ok, at this point, we know that we are masking the result of the
154 // ADD down to exactly one bit. If the constant we are adding has
155 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000156 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000157
158 // Check to see if any bits below the one bit set in AndRHSV are set.
Craig Topper73ba1c82017-06-07 07:40:37 +0000159 if ((AddRHS & (AndRHSV - 1)).isNullValue()) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000160 // If not, the only thing that can effect the output of the AND is
161 // the bit specified by AndRHSV. If that bit is set, the effect of
162 // the XOR is to toggle the bit. If it is clear, then the ADD has
163 // no effect.
Craig Topper73ba1c82017-06-07 07:40:37 +0000164 if ((AddRHS & AndRHSV).isNullValue()) { // Bit is not set, noop
Chris Lattner0a8191e2010-01-05 07:50:36 +0000165 TheAnd.setOperand(0, X);
166 return &TheAnd;
167 } else {
168 // Pull the XOR out of the AND.
Craig Topperbb4069e2017-07-07 23:16:26 +0000169 Value *NewAnd = Builder.CreateAnd(X, AndRHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000170 NewAnd->takeName(Op);
171 return BinaryOperator::CreateXor(NewAnd, AndRHS);
172 }
173 }
174 }
175 }
176 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000177 }
Craig Topperf40110f2014-04-25 05:29:35 +0000178 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000179}
180
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000181/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000182/// (V < Lo || V >= Hi). This method expects that Lo <= Hi. IsSigned indicates
183/// whether to treat V, Lo, and Hi as signed or not.
Sanjay Patel85d79742016-08-31 19:49:56 +0000184Value *InstCombiner::insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
Chris Lattner067459c2010-03-05 08:46:26 +0000185 bool isSigned, bool Inside) {
Sanjay Patel85d79742016-08-31 19:49:56 +0000186 assert((isSigned ? Lo.sle(Hi) : Lo.ule(Hi)) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000187 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000188
Sanjay Patel85d79742016-08-31 19:49:56 +0000189 Type *Ty = V->getType();
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000190 if (Lo == Hi)
Sanjay Patel85d79742016-08-31 19:49:56 +0000191 return Inside ? ConstantInt::getFalse(Ty) : ConstantInt::getTrue(Ty);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000192
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000193 // V >= Min && V < Hi --> V < Hi
194 // V < Min || V >= Hi --> V >= Hi
195 ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
Sanjay Patel85d79742016-08-31 19:49:56 +0000196 if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000197 Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
Craig Topperbb4069e2017-07-07 23:16:26 +0000198 return Builder.CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000199 }
200
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000201 // V >= Lo && V < Hi --> V - Lo u< Hi - Lo
202 // V < Lo || V >= Hi --> V - Lo u>= Hi - Lo
Sanjay Patel85d79742016-08-31 19:49:56 +0000203 Value *VMinusLo =
Craig Topperbb4069e2017-07-07 23:16:26 +0000204 Builder.CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
Sanjay Patel85d79742016-08-31 19:49:56 +0000205 Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
Craig Topperbb4069e2017-07-07 23:16:26 +0000206 return Builder.CreateICmp(Pred, VMinusLo, HiMinusLo);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000207}
208
Sanjay Patel77bf6222017-04-03 16:53:12 +0000209/// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
210/// that can be simplified.
211/// One of A and B is considered the mask. The other is the value. This is
212/// described as the "AMask" or "BMask" part of the enum. If the enum contains
213/// only "Mask", then both A and B can be considered masks. If A is the mask,
214/// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
215/// If both A and C are constants, this proof is also easy.
216/// For the following explanations, we assume that A is the mask.
217///
218/// "AllOnes" declares that the comparison is true only if (A & B) == A or all
219/// bits of A are set in B.
220/// Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
221///
222/// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
223/// bits of A are cleared in B.
224/// Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
225///
226/// "Mixed" declares that (A & B) == C and C might or might not contain any
227/// number of one bits and zero bits.
228/// Example: (icmp eq (A & 3), 1) -> AMask_Mixed
229///
230/// "Not" means that in above descriptions "==" should be replaced by "!=".
231/// Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
232///
Owen Anderson3fe002d2010-09-08 22:16:17 +0000233/// If the mask A contains a single bit, then the following is equivalent:
234/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
235/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
236enum MaskedICmpType {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000237 AMask_AllOnes = 1,
238 AMask_NotAllOnes = 2,
239 BMask_AllOnes = 4,
240 BMask_NotAllOnes = 8,
241 Mask_AllZeros = 16,
242 Mask_NotAllZeros = 32,
243 AMask_Mixed = 64,
244 AMask_NotMixed = 128,
245 BMask_Mixed = 256,
246 BMask_NotMixed = 512
Owen Anderson3fe002d2010-09-08 22:16:17 +0000247};
248
Sanjay Patel77bf6222017-04-03 16:53:12 +0000249/// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
250/// satisfies.
251static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
252 ICmpInst::Predicate Pred) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000253 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
254 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
255 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000256 bool IsEq = (Pred == ICmpInst::ICMP_EQ);
257 bool IsAPow2 = (ACst && !ACst->isZero() && ACst->getValue().isPowerOf2());
258 bool IsBPow2 = (BCst && !BCst->isZero() && BCst->getValue().isPowerOf2());
259 unsigned MaskVal = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000260 if (CCst && CCst->isZero()) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000261 // if C is zero, then both A and B qualify as mask
Sanjay Patel77bf6222017-04-03 16:53:12 +0000262 MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
263 : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
264 if (IsAPow2)
265 MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
266 : (AMask_AllOnes | AMask_Mixed));
267 if (IsBPow2)
268 MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
269 : (BMask_AllOnes | BMask_Mixed));
270 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000271 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000272
Owen Anderson3fe002d2010-09-08 22:16:17 +0000273 if (A == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000274 MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
275 : (AMask_NotAllOnes | AMask_NotMixed));
276 if (IsAPow2)
277 MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
278 : (Mask_AllZeros | AMask_Mixed));
279 } else if (ACst && CCst && ConstantExpr::getAnd(ACst, CCst) == CCst) {
280 MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000281 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000282
Craig Topperae48cb22012-12-20 07:15:54 +0000283 if (B == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000284 MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
285 : (BMask_NotAllOnes | BMask_NotMixed));
286 if (IsBPow2)
287 MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
288 : (Mask_AllZeros | BMask_Mixed));
289 } else if (BCst && CCst && ConstantExpr::getAnd(BCst, CCst) == CCst) {
290 MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000291 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000292
293 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000294}
295
Tim Northoverc0756c42013-09-04 11:57:13 +0000296/// Convert an analysis of a masked ICmp into its equivalent if all boolean
297/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
298/// is adjacent to the corresponding normal flag (recording ==), this just
299/// involves swapping those bits over.
300static unsigned conjugateICmpMask(unsigned Mask) {
301 unsigned NewMask;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000302 NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
303 AMask_Mixed | BMask_Mixed))
Tim Northoverc0756c42013-09-04 11:57:13 +0000304 << 1;
305
Sanjay Patel77bf6222017-04-03 16:53:12 +0000306 NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
307 AMask_NotMixed | BMask_NotMixed))
308 >> 1;
Tim Northoverc0756c42013-09-04 11:57:13 +0000309
310 return NewMask;
311}
312
Sanjay Patel77bf6222017-04-03 16:53:12 +0000313/// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
314/// Return the set of pattern classes (from MaskedICmpType) that both LHS and
315/// RHS satisfy.
316static unsigned getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C,
317 Value *&D, Value *&E, ICmpInst *LHS,
318 ICmpInst *RHS,
319 ICmpInst::Predicate &PredL,
320 ICmpInst::Predicate &PredR) {
321 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
322 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000323 // vectors are not (yet?) supported
Sanjay Patel77bf6222017-04-03 16:53:12 +0000324 if (LHS->getOperand(0)->getType()->isVectorTy())
325 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000326
327 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000328 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000329 // and L11 & L12 == L21 & L22. The same goes for RHS.
330 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000331 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000332 // above.
333 Value *L1 = LHS->getOperand(0);
334 Value *L2 = LHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000335 Value *L11, *L12, *L21, *L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000336 // Check whether the icmp can be decomposed into a bit test.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000337 if (decomposeBitTestICmp(LHS, PredL, L11, L12, L2)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000338 L21 = L22 = L1 = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000339 } else {
340 // Look for ANDs in the LHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000341 if (!L1->getType()->isIntegerTy()) {
342 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000343 L11 = L12 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000344 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
345 // Any icmp can be viewed as being trivially masked; if it allows us to
346 // remove one, it's worth it.
347 L11 = L1;
348 L12 = Constant::getAllOnesValue(L1->getType());
349 }
350
351 if (!L2->getType()->isIntegerTy()) {
352 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000353 L21 = L22 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000354 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
355 L21 = L2;
356 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000357 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000358 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000359
360 // Bail if LHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000361 if (!ICmpInst::isEquality(PredL))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000362 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000363
364 Value *R1 = RHS->getOperand(0);
365 Value *R2 = RHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000366 Value *R11, *R12;
367 bool Ok = false;
368 if (decomposeBitTestICmp(RHS, PredR, R11, R12, R2)) {
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000369 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000370 A = R11;
371 D = R12;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000372 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000373 A = R12;
374 D = R11;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000375 } else {
376 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000377 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000378 E = R2;
379 R1 = nullptr;
380 Ok = true;
Tim Northoverdc647a22013-09-04 11:57:17 +0000381 } else if (R1->getType()->isIntegerTy()) {
382 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
383 // As before, model no mask as a trivial mask if it'll let us do an
Mayur Pandey75b76c62014-08-19 06:41:55 +0000384 // optimization.
Tim Northoverdc647a22013-09-04 11:57:17 +0000385 R11 = R1;
386 R12 = Constant::getAllOnesValue(R1->getType());
387 }
388
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000389 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000390 A = R11;
391 D = R12;
392 E = R2;
393 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000394 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000395 A = R12;
396 D = R11;
397 E = R2;
398 Ok = true;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000399 }
400 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000401
402 // Bail if RHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000403 if (!ICmpInst::isEquality(PredR))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000404 return 0;
405
Chad Rosier58919cc2016-05-09 21:37:43 +0000406 // Look for ANDs on the right side of the RHS icmp.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000407 if (!Ok && R2->getType()->isIntegerTy()) {
Tim Northoverdc647a22013-09-04 11:57:17 +0000408 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
409 R11 = R2;
410 R12 = Constant::getAllOnesValue(R2->getType());
411 }
412
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000413 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000414 A = R11;
415 D = R12;
416 E = R1;
417 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000418 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000419 A = R12;
420 D = R11;
421 E = R1;
422 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000423 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000424 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000425 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000426 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000427 if (!Ok)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000428 return 0;
429
430 if (L11 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000431 B = L12;
432 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000433 } else if (L12 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000434 B = L11;
435 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000436 } else if (L21 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000437 B = L22;
438 C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000439 } else if (L22 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000440 B = L21;
441 C = L1;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000442 }
443
Sanjay Patel77bf6222017-04-03 16:53:12 +0000444 unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
445 unsigned RightType = getMaskedICmpType(A, D, E, PredR);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000446 return LeftType & RightType;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000447}
Sanjay Patel18549272015-09-08 18:24:36 +0000448
449/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
450/// into a single (icmp(A & X) ==/!= Y).
David Majnemer1a3327b2014-11-18 09:31:36 +0000451static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
Craig Topperbb4069e2017-07-07 23:16:26 +0000452 llvm::InstCombiner::BuilderTy &Builder) {
Craig Topperf40110f2014-04-25 05:29:35 +0000453 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000454 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
455 unsigned Mask =
456 getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
457 if (Mask == 0)
458 return nullptr;
459
460 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
461 "Expected equality predicates for masked type of icmps.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000462
Tim Northoverc0756c42013-09-04 11:57:13 +0000463 // In full generality:
464 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
465 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
466 //
467 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
468 // equivalent to (icmp (A & X) !Op Y).
469 //
470 // Therefore, we can pretend for the rest of this function that we're dealing
471 // with the conjunction, provided we flip the sense of any comparisons (both
472 // input and output).
473
474 // In most cases we're going to produce an EQ for the "&&" case.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000475 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Tim Northoverc0756c42013-09-04 11:57:13 +0000476 if (!IsAnd) {
477 // Convert the masking analysis into its equivalent with negated
478 // comparisons.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000479 Mask = conjugateICmpMask(Mask);
Tim Northoverc0756c42013-09-04 11:57:13 +0000480 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000481
Sanjay Patel77bf6222017-04-03 16:53:12 +0000482 if (Mask & Mask_AllZeros) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000483 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000484 // -> (icmp eq (A & (B|D)), 0)
Craig Topperbb4069e2017-07-07 23:16:26 +0000485 Value *NewOr = Builder.CreateOr(B, D);
486 Value *NewAnd = Builder.CreateAnd(A, NewOr);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000487 // We can't use C as zero because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000488 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000489 // with B and D, having a single bit set.
490 Value *Zero = Constant::getNullValue(A->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +0000491 return Builder.CreateICmp(NewCC, NewAnd, Zero);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000492 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000493 if (Mask & BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000494 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000495 // -> (icmp eq (A & (B|D)), (B|D))
Craig Topperbb4069e2017-07-07 23:16:26 +0000496 Value *NewOr = Builder.CreateOr(B, D);
497 Value *NewAnd = Builder.CreateAnd(A, NewOr);
498 return Builder.CreateICmp(NewCC, NewAnd, NewOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000499 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000500 if (Mask & AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000501 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000502 // -> (icmp eq (A & (B&D)), A)
Craig Topperbb4069e2017-07-07 23:16:26 +0000503 Value *NewAnd1 = Builder.CreateAnd(B, D);
504 Value *NewAnd2 = Builder.CreateAnd(A, NewAnd1);
505 return Builder.CreateICmp(NewCC, NewAnd2, A);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000506 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000507
508 // Remaining cases assume at least that B and D are constant, and depend on
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000509 // their actual values. This isn't strictly necessary, just a "handle the
Tim Northoverc0756c42013-09-04 11:57:13 +0000510 // easy cases for now" decision.
511 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000512 if (!BCst)
513 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000514 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000515 if (!DCst)
516 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000517
Sanjay Patel77bf6222017-04-03 16:53:12 +0000518 if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000519 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
520 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
521 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
522 // Only valid if one of the masks is a superset of the other (check "B&D" is
523 // the same as either B or D).
524 APInt NewMask = BCst->getValue() & DCst->getValue();
525
526 if (NewMask == BCst->getValue())
527 return LHS;
528 else if (NewMask == DCst->getValue())
529 return RHS;
530 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000531
532 if (Mask & AMask_NotAllOnes) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000533 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
534 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
535 // Only valid if one of the masks is a superset of the other (check "B|D" is
536 // the same as either B or D).
537 APInt NewMask = BCst->getValue() | DCst->getValue();
538
539 if (NewMask == BCst->getValue())
540 return LHS;
541 else if (NewMask == DCst->getValue())
542 return RHS;
543 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000544
545 if (Mask & BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000546 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000547 // We already know that B & C == C && D & E == E.
548 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
549 // C and E, which are shared by both the mask B and the mask D, don't
550 // contradict, then we can transform to
551 // -> (icmp eq (A & (B|D)), (C|E))
552 // Currently, we only handle the case of B, C, D, and E being constant.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000553 // We can't simply use C and E because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000554 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000555 // with B and D, having a single bit set.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000556 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000557 if (!CCst)
558 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000559 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000560 if (!ECst)
561 return nullptr;
562 if (PredL != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000563 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000564 if (PredR != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000565 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000566
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000567 // If there is a conflict, we should actually return a false for the
568 // whole construct.
David Majnemer1a3327b2014-11-18 09:31:36 +0000569 if (((BCst->getValue() & DCst->getValue()) &
Craig Topper73ba1c82017-06-07 07:40:37 +0000570 (CCst->getValue() ^ ECst->getValue())).getBoolValue())
David Majnemer6fdb6b82014-11-18 09:31:41 +0000571 return ConstantInt::get(LHS->getType(), !IsAnd);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000572
Craig Topperbb4069e2017-07-07 23:16:26 +0000573 Value *NewOr1 = Builder.CreateOr(B, D);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000574 Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
Craig Topperbb4069e2017-07-07 23:16:26 +0000575 Value *NewAnd = Builder.CreateAnd(A, NewOr1);
576 return Builder.CreateICmp(NewCC, NewAnd, NewOr2);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000577 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000578
Craig Topperf40110f2014-04-25 05:29:35 +0000579 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000580}
581
Erik Ecksteind1817522014-12-03 10:39:15 +0000582/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
583/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
584/// If \p Inverted is true then the check is for the inverted range, e.g.
585/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
586Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
587 bool Inverted) {
588 // Check the lower range comparison, e.g. x >= 0
589 // InstCombine already ensured that if there is a constant it's on the RHS.
590 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
591 if (!RangeStart)
592 return nullptr;
593
594 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
595 Cmp0->getPredicate());
596
597 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
598 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
599 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
600 return nullptr;
601
602 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
603 Cmp1->getPredicate());
604
605 Value *Input = Cmp0->getOperand(0);
606 Value *RangeEnd;
607 if (Cmp1->getOperand(0) == Input) {
608 // For the upper range compare we have: icmp x, n
609 RangeEnd = Cmp1->getOperand(1);
610 } else if (Cmp1->getOperand(1) == Input) {
611 // For the upper range compare we have: icmp n, x
612 RangeEnd = Cmp1->getOperand(0);
613 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
614 } else {
615 return nullptr;
616 }
617
618 // Check the upper range comparison, e.g. x < n
619 ICmpInst::Predicate NewPred;
620 switch (Pred1) {
621 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
622 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
623 default: return nullptr;
624 }
625
626 // This simplification is only valid if the upper range is not negative.
Craig Topper1a36b7d2017-05-15 06:39:41 +0000627 KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
628 if (!Known.isNonNegative())
Erik Ecksteind1817522014-12-03 10:39:15 +0000629 return nullptr;
630
631 if (Inverted)
632 NewPred = ICmpInst::getInversePredicate(NewPred);
633
Craig Topperbb4069e2017-07-07 23:16:26 +0000634 return Builder.CreateICmp(NewPred, Input, RangeEnd);
Erik Ecksteind1817522014-12-03 10:39:15 +0000635}
636
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000637static Value *
638foldAndOrOfEqualityCmpsWithConstants(ICmpInst *LHS, ICmpInst *RHS,
639 bool JoinedByAnd,
Craig Topperbb4069e2017-07-07 23:16:26 +0000640 InstCombiner::BuilderTy &Builder) {
Sanjay Patelef9f5862017-04-15 17:55:06 +0000641 Value *X = LHS->getOperand(0);
642 if (X != RHS->getOperand(0))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000643 return nullptr;
644
Sanjay Patelef9f5862017-04-15 17:55:06 +0000645 const APInt *C1, *C2;
646 if (!match(LHS->getOperand(1), m_APInt(C1)) ||
647 !match(RHS->getOperand(1), m_APInt(C2)))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000648 return nullptr;
649
650 // We only handle (X != C1 && X != C2) and (X == C1 || X == C2).
651 ICmpInst::Predicate Pred = LHS->getPredicate();
652 if (Pred != RHS->getPredicate())
653 return nullptr;
654 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
655 return nullptr;
656 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
657 return nullptr;
658
659 // The larger unsigned constant goes on the right.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000660 if (C1->ugt(*C2))
661 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000662
Sanjay Patelef9f5862017-04-15 17:55:06 +0000663 APInt Xor = *C1 ^ *C2;
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000664 if (Xor.isPowerOf2()) {
665 // If LHSC and RHSC differ by only one bit, then set that bit in X and
666 // compare against the larger constant:
667 // (X == C1 || X == C2) --> (X | (C1 ^ C2)) == C2
668 // (X != C1 && X != C2) --> (X | (C1 ^ C2)) != C2
669 // We choose an 'or' with a Pow2 constant rather than the inverse mask with
670 // 'and' because that may lead to smaller codegen from a smaller constant.
Craig Topperbb4069e2017-07-07 23:16:26 +0000671 Value *Or = Builder.CreateOr(X, ConstantInt::get(X->getType(), Xor));
672 return Builder.CreateICmp(Pred, Or, ConstantInt::get(X->getType(), *C2));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000673 }
674
675 // Special case: get the ordering right when the values wrap around zero.
676 // Ie, we assumed the constants were unsigned when swapping earlier.
Craig Topper73ba1c82017-06-07 07:40:37 +0000677 if (C1->isNullValue() && C2->isAllOnesValue())
Sanjay Patelef9f5862017-04-15 17:55:06 +0000678 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000679
Sanjay Patelef9f5862017-04-15 17:55:06 +0000680 if (*C1 == *C2 - 1) {
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000681 // (X == 13 || X == 14) --> X - 13 <=u 1
682 // (X != 13 && X != 14) --> X - 13 >u 1
683 // An 'add' is the canonical IR form, so favor that over a 'sub'.
Craig Topperbb4069e2017-07-07 23:16:26 +0000684 Value *Add = Builder.CreateAdd(X, ConstantInt::get(X->getType(), -(*C1)));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000685 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
Craig Topperbb4069e2017-07-07 23:16:26 +0000686 return Builder.CreateICmp(NewPred, Add, ConstantInt::get(X->getType(), 1));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000687 }
688
689 return nullptr;
690}
691
Craig Topperda6ea0d2017-06-16 05:10:37 +0000692// Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
693// Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
694Value *InstCombiner::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS,
695 bool JoinedByAnd,
696 Instruction &CxtI) {
697 ICmpInst::Predicate Pred = LHS->getPredicate();
698 if (Pred != RHS->getPredicate())
699 return nullptr;
700 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
701 return nullptr;
702 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
703 return nullptr;
704
705 // TODO support vector splats
706 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
707 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
708 if (!LHSC || !RHSC || !LHSC->isZero() || !RHSC->isZero())
709 return nullptr;
710
711 Value *A, *B, *C, *D;
712 if (match(LHS->getOperand(0), m_And(m_Value(A), m_Value(B))) &&
713 match(RHS->getOperand(0), m_And(m_Value(C), m_Value(D)))) {
714 if (A == D || B == D)
715 std::swap(C, D);
716 if (B == C)
717 std::swap(A, B);
718
719 if (A == C &&
720 isKnownToBeAPowerOfTwo(B, false, 0, &CxtI) &&
721 isKnownToBeAPowerOfTwo(D, false, 0, &CxtI)) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000722 Value *Mask = Builder.CreateOr(B, D);
723 Value *Masked = Builder.CreateAnd(A, Mask);
Craig Topperda6ea0d2017-06-16 05:10:37 +0000724 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Craig Topperbb4069e2017-07-07 23:16:26 +0000725 return Builder.CreateICmp(NewPred, Masked, Mask);
Craig Topperda6ea0d2017-06-16 05:10:37 +0000726 }
727 }
728
729 return nullptr;
730}
731
Sanjay Patel18549272015-09-08 18:24:36 +0000732/// Fold (icmp)&(icmp) if possible.
Craig Topperda6ea0d2017-06-16 05:10:37 +0000733Value *InstCombiner::foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS,
734 Instruction &CxtI) {
735 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
736 // if K1 and K2 are a one-bit mask.
737 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, true, CxtI))
738 return V;
739
Sanjay Patel519a87a2017-04-05 17:38:34 +0000740 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000741
742 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000743 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000744 if (LHS->getOperand(0) == RHS->getOperand(1) &&
745 LHS->getOperand(1) == RHS->getOperand(0))
746 LHS->swapOperands();
747 if (LHS->getOperand(0) == RHS->getOperand(0) &&
748 LHS->getOperand(1) == RHS->getOperand(1)) {
749 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
750 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
751 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000752 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000753 }
754 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000755
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000756 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000757 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000758 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000759
Erik Ecksteind1817522014-12-03 10:39:15 +0000760 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
761 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
762 return V;
763
764 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
765 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
766 return V;
767
Sanjay Patelef9f5862017-04-15 17:55:06 +0000768 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, true, Builder))
769 return V;
770
Chris Lattner0a8191e2010-01-05 07:50:36 +0000771 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Sanjay Patele4159d22017-04-10 19:38:36 +0000772 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000773 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
774 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
775 if (!LHSC || !RHSC)
776 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000777
Sanjay Patel519a87a2017-04-05 17:38:34 +0000778 if (LHSC == RHSC && PredL == PredR) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000779 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000780 // where C is a power of 2 or
Chris Lattner0a8191e2010-01-05 07:50:36 +0000781 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000782 if ((PredL == ICmpInst::ICMP_ULT && LHSC->getValue().isPowerOf2()) ||
783 (PredL == ICmpInst::ICMP_EQ && LHSC->isZero())) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000784 Value *NewOr = Builder.CreateOr(LHS0, RHS0);
785 return Builder.CreateICmp(PredL, NewOr, LHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000786 }
787 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000788
Benjamin Kramer101720f2011-04-28 20:09:57 +0000789 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000790 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000791 // iff the lower bits of C2 and CA are zero.
Sanjay Patel519a87a2017-04-05 17:38:34 +0000792 if (PredL == ICmpInst::ICMP_EQ && PredL == PredR && LHS->hasOneUse() &&
793 RHS->hasOneUse()) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000794 Value *V;
Sanjay Patel519a87a2017-04-05 17:38:34 +0000795 ConstantInt *AndC, *SmallC = nullptr, *BigC = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000796
797 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000798 // (and x, CA) == C2 & (trunc x) == C1
Sanjay Patele4159d22017-04-10 19:38:36 +0000799 if (match(RHS0, m_Trunc(m_Value(V))) &&
800 match(LHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000801 SmallC = RHSC;
802 BigC = LHSC;
Sanjay Patele4159d22017-04-10 19:38:36 +0000803 } else if (match(LHS0, m_Trunc(m_Value(V))) &&
804 match(RHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000805 SmallC = LHSC;
806 BigC = RHSC;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000807 }
808
Sanjay Patel519a87a2017-04-05 17:38:34 +0000809 if (SmallC && BigC) {
810 unsigned BigBitSize = BigC->getType()->getBitWidth();
811 unsigned SmallBitSize = SmallC->getType()->getBitWidth();
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000812
813 // Check that the low bits are zero.
814 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Craig Topper73ba1c82017-06-07 07:40:37 +0000815 if ((Low & AndC->getValue()).isNullValue() &&
816 (Low & BigC->getValue()).isNullValue()) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000817 Value *NewAnd = Builder.CreateAnd(V, Low | AndC->getValue());
Sanjay Patel519a87a2017-04-05 17:38:34 +0000818 APInt N = SmallC->getValue().zext(BigBitSize) | BigC->getValue();
819 Value *NewVal = ConstantInt::get(AndC->getType()->getContext(), N);
Craig Topperbb4069e2017-07-07 23:16:26 +0000820 return Builder.CreateICmp(PredL, NewAnd, NewVal);
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000821 }
822 }
823 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000824
Chris Lattner0a8191e2010-01-05 07:50:36 +0000825 // From here on, we only handle:
826 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +0000827 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000828 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000829
Sanjay Patel519a87a2017-04-05 17:38:34 +0000830 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
831 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
832 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
833 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
834 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000835 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000836
Chris Lattner0a8191e2010-01-05 07:50:36 +0000837 // We can't fold (ugt x, C) & (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +0000838 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +0000839 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000840
Chris Lattner0a8191e2010-01-05 07:50:36 +0000841 // Ensure that the larger constant is on the RHS.
842 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +0000843 if (CmpInst::isSigned(PredL) ||
844 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +0000845 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +0000846 else
847 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000848
Chris Lattner0a8191e2010-01-05 07:50:36 +0000849 if (ShouldSwap) {
850 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000851 std::swap(LHSC, RHSC);
852 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000853 }
854
Dan Gohman4a618822010-02-10 16:03:48 +0000855 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000856 // comparing a value against two constants and and'ing the result
857 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +0000858 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
859 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +0000860 // are not equal and that the larger constant is on the RHS
Sanjay Patel519a87a2017-04-05 17:38:34 +0000861 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000862
Sanjay Patel519a87a2017-04-05 17:38:34 +0000863 switch (PredL) {
864 default:
865 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000866 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000867 switch (PredR) {
868 default:
869 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000870 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000871 if (LHSC == SubOne(RHSC)) // (X != 13 & X u< 14) -> X < 13
Craig Topperbb4069e2017-07-07 23:16:26 +0000872 return Builder.CreateICmpULT(LHS0, LHSC);
Craig Topper79ab6432017-07-06 18:39:47 +0000873 if (LHSC->isZero()) // (X != 0 & X u< 14) -> X-1 u< 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000874 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
Sanjay Patel85d79742016-08-31 19:49:56 +0000875 false, true);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000876 break; // (X != 13 & X u< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000877 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000878 if (LHSC == SubOne(RHSC)) // (X != 13 & X s< 14) -> X < 13
Craig Topperbb4069e2017-07-07 23:16:26 +0000879 return Builder.CreateICmpSLT(LHS0, LHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000880 break; // (X != 13 & X s< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000881 case ICmpInst::ICMP_NE:
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000882 // Potential folds for this case should already be handled.
883 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000884 }
885 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000886 case ICmpInst::ICMP_UGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000887 switch (PredR) {
888 default:
889 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000890 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000891 if (RHSC == AddOne(LHSC)) // (X u> 13 & X != 14) -> X u> 14
Craig Topperbb4069e2017-07-07 23:16:26 +0000892 return Builder.CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000893 break; // (X u> 13 & X != 15) -> no change
894 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000895 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
896 false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000897 }
898 break;
899 case ICmpInst::ICMP_SGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000900 switch (PredR) {
901 default:
902 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000903 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000904 if (RHSC == AddOne(LHSC)) // (X s> 13 & X != 14) -> X s> 14
Craig Topperbb4069e2017-07-07 23:16:26 +0000905 return Builder.CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000906 break; // (X s> 13 & X != 15) -> no change
907 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000908 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(), true,
Sanjay Patel519a87a2017-04-05 17:38:34 +0000909 true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000910 }
911 break;
912 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000913
Craig Topperf40110f2014-04-25 05:29:35 +0000914 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000915}
916
Sanjay Patel18549272015-09-08 18:24:36 +0000917/// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
918/// a Value which should already be inserted into the function.
Sanjay Patel5e456b92017-05-18 20:53:16 +0000919Value *InstCombiner::foldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +0000920 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
921 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
922 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
923
924 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
925 // Swap RHS operands to match LHS.
926 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
927 std::swap(Op1LHS, Op1RHS);
928 }
929
930 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
931 // Suppose the relation between x and y is R, where R is one of
932 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
933 // testing the desired relations.
934 //
935 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
936 // bool(R & CC0) && bool(R & CC1)
937 // = bool((R & CC0) & (R & CC1))
938 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
939 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
940 return getFCmpValue(getFCmpCode(Op0CC) & getFCmpCode(Op1CC), Op0LHS, Op0RHS,
941 Builder);
942
Chris Lattner0a8191e2010-01-05 07:50:36 +0000943 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
944 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +0000945 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +0000946 return nullptr;
Benjamin Kramere89c7052013-04-12 21:56:23 +0000947
Chris Lattner0a8191e2010-01-05 07:50:36 +0000948 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
949 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
950 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
951 // If either of the constants are nans, then the whole thing returns
952 // false.
953 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Craig Topperbb4069e2017-07-07 23:16:26 +0000954 return Builder.getFalse();
955 return Builder.CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000956 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000957
Chris Lattner0a8191e2010-01-05 07:50:36 +0000958 // Handle vector zeros. This occurs because the canonical form of
959 // "fcmp ord x,x" is "fcmp ord x, 0".
960 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
961 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Craig Topperbb4069e2017-07-07 23:16:26 +0000962 return Builder.CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +0000963 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000964 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000965
Craig Topperf40110f2014-04-25 05:29:35 +0000966 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000967}
968
Sanjay Patelb54e62f2015-09-08 20:14:13 +0000969/// Match De Morgan's Laws:
970/// (~A & ~B) == (~(A | B))
971/// (~A | ~B) == (~(A & B))
972static Instruction *matchDeMorgansLaws(BinaryOperator &I,
Sanjay Patel7caaa792017-05-09 20:05:05 +0000973 InstCombiner::BuilderTy &Builder) {
Sanjay Patelb54e62f2015-09-08 20:14:13 +0000974 auto Opcode = I.getOpcode();
975 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
976 "Trying to match De Morgan's Laws with something other than and/or");
977
Sanjay Patel7caaa792017-05-09 20:05:05 +0000978 // Flip the logic operation.
979 Opcode = (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
980
981 Value *A, *B;
982 if (match(I.getOperand(0), m_OneUse(m_Not(m_Value(A)))) &&
983 match(I.getOperand(1), m_OneUse(m_Not(m_Value(B)))) &&
984 !IsFreeToInvert(A, A->hasOneUse()) &&
985 !IsFreeToInvert(B, B->hasOneUse())) {
986 Value *AndOr = Builder.CreateBinOp(Opcode, A, B, I.getName() + ".demorgan");
987 return BinaryOperator::CreateNot(AndOr);
988 }
Sanjay Patelb54e62f2015-09-08 20:14:13 +0000989
990 return nullptr;
991}
992
Tobias Grosser8ef834c2016-07-19 09:06:08 +0000993bool InstCombiner::shouldOptimizeCast(CastInst *CI) {
994 Value *CastSrc = CI->getOperand(0);
995
996 // Noop casts and casts of constants should be eliminated trivially.
997 if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
998 return false;
999
1000 // If this cast is paired with another cast that can be eliminated, we prefer
1001 // to have it eliminated.
1002 if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
1003 if (isEliminableCastPair(PrecedingCI, CI))
1004 return false;
1005
1006 // If this is a vector sext from a compare, then we don't want to break the
1007 // idiom where each element of the extended vector is either zero or all ones.
1008 if (CI->getOpcode() == Instruction::SExt &&
1009 isa<CmpInst>(CastSrc) && CI->getDestTy()->isVectorTy())
1010 return false;
1011
1012 return true;
1013}
1014
Sanjay Patel60312bc42016-09-12 00:16:23 +00001015/// Fold {and,or,xor} (cast X), C.
1016static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
Craig Topperbb4069e2017-07-07 23:16:26 +00001017 InstCombiner::BuilderTy &Builder) {
Sanjay Patel60312bc42016-09-12 00:16:23 +00001018 Constant *C;
1019 if (!match(Logic.getOperand(1), m_Constant(C)))
1020 return nullptr;
1021
1022 auto LogicOpc = Logic.getOpcode();
1023 Type *DestTy = Logic.getType();
1024 Type *SrcTy = Cast->getSrcTy();
1025
Craig Topperae9b87d2017-08-02 20:25:56 +00001026 // Move the logic operation ahead of a zext or sext if the constant is
1027 // unchanged in the smaller source type. Performing the logic in a smaller
1028 // type may provide more information to later folds, and the smaller logic
1029 // instruction may be cheaper (particularly in the case of vectors).
Sanjay Patel60312bc42016-09-12 00:16:23 +00001030 Value *X;
Sanjay Patel60312bc42016-09-12 00:16:23 +00001031 if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1032 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1033 Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1034 if (ZextTruncC == C) {
1035 // LogicOpc (zext X), C --> zext (LogicOpc X, C)
Craig Topperbb4069e2017-07-07 23:16:26 +00001036 Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
Sanjay Patel60312bc42016-09-12 00:16:23 +00001037 return new ZExtInst(NewOp, DestTy);
1038 }
1039 }
1040
Craig Topperae9b87d2017-08-02 20:25:56 +00001041 if (match(Cast, m_OneUse(m_SExt(m_Value(X))))) {
1042 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1043 Constant *SextTruncC = ConstantExpr::getSExt(TruncC, DestTy);
1044 if (SextTruncC == C) {
1045 // LogicOpc (sext X), C --> sext (LogicOpc X, C)
1046 Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
1047 return new SExtInst(NewOp, DestTy);
1048 }
1049 }
1050
Sanjay Patel60312bc42016-09-12 00:16:23 +00001051 return nullptr;
1052}
1053
1054/// Fold {and,or,xor} (cast X), Y.
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001055Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001056 auto LogicOpc = I.getOpcode();
Sanjay Patel1e6ca442016-11-22 22:54:36 +00001057 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001058
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001059 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001060 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
Sanjay Patel9bba7502016-03-03 19:19:04 +00001061 if (!Cast0)
Sanjay Patel7d0d8102016-02-23 16:59:21 +00001062 return nullptr;
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001063
Sanjay Patel9bba7502016-03-03 19:19:04 +00001064 // This must be a cast from an integer or integer vector source type to allow
1065 // transformation of the logic operation to the source type.
1066 Type *DestTy = I.getType();
Sanjay Patel713f25e2016-02-23 17:41:34 +00001067 Type *SrcTy = Cast0->getSrcTy();
Sanjay Patel9bba7502016-03-03 19:19:04 +00001068 if (!SrcTy->isIntOrIntVectorTy())
1069 return nullptr;
1070
Sanjay Patel60312bc42016-09-12 00:16:23 +00001071 if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1072 return Ret;
Sanjay Patel0753c062016-07-21 00:24:18 +00001073
Sanjay Patel9bba7502016-03-03 19:19:04 +00001074 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1075 if (!Cast1)
1076 return nullptr;
1077
1078 // Both operands of the logic operation are casts. The casts must be of the
1079 // same type for reduction.
1080 auto CastOpcode = Cast0->getOpcode();
1081 if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
Sanjay Patel713f25e2016-02-23 17:41:34 +00001082 return nullptr;
1083
1084 Value *Cast0Src = Cast0->getOperand(0);
1085 Value *Cast1Src = Cast1->getOperand(0);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001086
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001087 // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
Tobias Grosser8757e382016-08-03 19:30:35 +00001088 if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001089 Value *NewOp = Builder.CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001090 I.getName());
Sanjay Patel713f25e2016-02-23 17:41:34 +00001091 return CastInst::Create(CastOpcode, NewOp, DestTy);
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001092 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001093
Sanjay Pateldbbaca02016-02-24 17:00:34 +00001094 // For now, only 'and'/'or' have optimizations after this.
1095 if (LogicOpc == Instruction::Xor)
1096 return nullptr;
1097
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001098 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001099 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001100 ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1101 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1102 if (ICmp0 && ICmp1) {
Craig Topperda6ea0d2017-06-16 05:10:37 +00001103 Value *Res = LogicOpc == Instruction::And ? foldAndOfICmps(ICmp0, ICmp1, I)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001104 : foldOrOfICmps(ICmp0, ICmp1, I);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001105 if (Res)
1106 return CastInst::Create(CastOpcode, Res, DestTy);
1107 return nullptr;
1108 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001109
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001110 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001111 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001112 FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1113 FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1114 if (FCmp0 && FCmp1) {
Sanjay Patel5e456b92017-05-18 20:53:16 +00001115 Value *Res = LogicOpc == Instruction::And ? foldAndOfFCmps(FCmp0, FCmp1)
1116 : foldOrOfFCmps(FCmp0, FCmp1);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001117 if (Res)
1118 return CastInst::Create(CastOpcode, Res, DestTy);
1119 return nullptr;
1120 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001121
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001122 return nullptr;
1123}
1124
Sanjay Patele0c26e02017-04-23 22:00:02 +00001125static Instruction *foldAndToXor(BinaryOperator &I,
1126 InstCombiner::BuilderTy &Builder) {
1127 assert(I.getOpcode() == Instruction::And);
1128 Value *Op0 = I.getOperand(0);
1129 Value *Op1 = I.getOperand(1);
1130 Value *A, *B;
1131
1132 // Operand complexity canonicalization guarantees that the 'or' is Op0.
1133 // (A | B) & ~(A & B) --> A ^ B
1134 // (A | B) & ~(B & A) --> A ^ B
1135 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1136 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B)))))
1137 return BinaryOperator::CreateXor(A, B);
1138
1139 // (A | ~B) & (~A | B) --> ~(A ^ B)
1140 // (A | ~B) & (B | ~A) --> ~(A ^ B)
1141 // (~B | A) & (~A | B) --> ~(A ^ B)
1142 // (~B | A) & (B | ~A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001143 if (Op0->hasOneUse() || Op1->hasOneUse())
1144 if (match(Op0, m_c_Or(m_Value(A), m_Not(m_Value(B)))) &&
1145 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B))))
1146 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001147
1148 return nullptr;
1149}
1150
1151static Instruction *foldOrToXor(BinaryOperator &I,
1152 InstCombiner::BuilderTy &Builder) {
1153 assert(I.getOpcode() == Instruction::Or);
1154 Value *Op0 = I.getOperand(0);
1155 Value *Op1 = I.getOperand(1);
1156 Value *A, *B;
1157
1158 // Operand complexity canonicalization guarantees that the 'and' is Op0.
1159 // (A & B) | ~(A | B) --> ~(A ^ B)
1160 // (A & B) | ~(B | A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001161 if (Op0->hasOneUse() || Op1->hasOneUse())
1162 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1163 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1164 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001165
1166 // (A & ~B) | (~A & B) --> A ^ B
1167 // (A & ~B) | (B & ~A) --> A ^ B
1168 // (~B & A) | (~A & B) --> A ^ B
1169 // (~B & A) | (B & ~A) --> A ^ B
1170 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
1171 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
1172 return BinaryOperator::CreateXor(A, B);
1173
1174 return nullptr;
1175}
1176
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001177// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1178// here. We should standardize that construct where it is needed or choose some
1179// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001180Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001181 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001182 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1183
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001184 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001185 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001186
Craig Toppera4205622017-06-09 03:21:29 +00001187 if (Value *V = SimplifyAndInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001188 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001189
Craig Topper9d4171a2012-12-20 07:09:41 +00001190 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001191 // purpose is to compute bits we don't care about.
1192 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001193 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001194
Sanjay Patele0c26e02017-04-23 22:00:02 +00001195 // Do this before using distributive laws to catch simple and/or/not patterns.
Craig Topperbb4069e2017-07-07 23:16:26 +00001196 if (Instruction *Xor = foldAndToXor(I, Builder))
Sanjay Patele0c26e02017-04-23 22:00:02 +00001197 return Xor;
1198
1199 // (A|B)&(A|C) -> A|(B&C) etc
1200 if (Value *V = SimplifyUsingDistributiveLaws(I))
1201 return replaceInstUsesWith(I, V);
1202
Craig Topper95e41422017-07-06 16:24:23 +00001203 if (Value *V = SimplifyBSwap(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001204 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001205
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001206 const APInt *C;
1207 if (match(Op1, m_APInt(C))) {
1208 Value *X, *Y;
1209 if (match(Op0, m_OneUse(m_LogicalShift(m_One(), m_Value(X)))) &&
1210 C->isOneValue()) {
1211 // (1 << X) & 1 --> zext(X == 0)
1212 // (1 >> X) & 1 --> zext(X == 0)
Sanjay Patel3437ee22017-07-15 17:26:01 +00001213 Value *IsZero = Builder.CreateICmpEQ(X, ConstantInt::get(I.getType(), 0));
1214 return new ZExtInst(IsZero, I.getType());
1215 }
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001216
Craig Toppera1693a22017-08-06 23:11:49 +00001217 const APInt *XorC;
1218 if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_APInt(XorC))))) {
1219 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1220 Constant *NewC = ConstantInt::get(I.getType(), *C & *XorC);
1221 Value *And = Builder.CreateAnd(X, Op1);
1222 And->takeName(Op0);
1223 return BinaryOperator::CreateXor(And, NewC);
1224 }
1225
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001226 // If the mask is only needed on one incoming arm, push the 'and' op up.
1227 if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_Value(Y)))) ||
1228 match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
1229 APInt NotAndMask(~(*C));
1230 BinaryOperator::BinaryOps BinOp = cast<BinaryOperator>(Op0)->getOpcode();
1231 if (MaskedValueIsZero(X, NotAndMask, 0, &I)) {
1232 // Not masking anything out for the LHS, move mask to RHS.
1233 // and ({x}or X, Y), C --> {x}or X, (and Y, C)
1234 Value *NewRHS = Builder.CreateAnd(Y, Op1, Y->getName() + ".masked");
1235 return BinaryOperator::Create(BinOp, X, NewRHS);
1236 }
1237 if (!isa<Constant>(Y) && MaskedValueIsZero(Y, NotAndMask, 0, &I)) {
1238 // Not masking anything out for the RHS, move mask to LHS.
1239 // and ({x}or X, Y), C --> {x}or (and X, C), Y
1240 Value *NewLHS = Builder.CreateAnd(X, Op1, X->getName() + ".masked");
1241 return BinaryOperator::Create(BinOp, NewLHS, Y);
1242 }
1243 }
Craig Toppera1693a22017-08-06 23:11:49 +00001244
Sanjay Patel3437ee22017-07-15 17:26:01 +00001245 }
Sanjay Patel55b9f882017-07-15 15:29:47 +00001246
Chris Lattner0a8191e2010-01-05 07:50:36 +00001247 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1248 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001249
1250 // Optimize a variety of ((val OP C1) & C2) combinations...
1251 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
David Majnemerde55c602017-01-17 18:08:06 +00001252 // ((C1 OP zext(X)) & C2) -> zext((C1-X) & C2) if C2 fits in the bitwidth
1253 // of X and OP behaves well when given trunc(C1) and X.
1254 switch (Op0I->getOpcode()) {
1255 default:
1256 break;
1257 case Instruction::Xor:
1258 case Instruction::Or:
1259 case Instruction::Mul:
1260 case Instruction::Add:
1261 case Instruction::Sub:
1262 Value *X;
1263 ConstantInt *C1;
Craig Topperb5194ee2017-04-12 05:49:28 +00001264 if (match(Op0I, m_c_BinOp(m_ZExt(m_Value(X)), m_ConstantInt(C1)))) {
David Majnemerde55c602017-01-17 18:08:06 +00001265 if (AndRHSMask.isIntN(X->getType()->getScalarSizeInBits())) {
1266 auto *TruncC1 = ConstantExpr::getTrunc(C1, X->getType());
1267 Value *BinOp;
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001268 Value *Op0LHS = Op0I->getOperand(0);
David Majnemerde55c602017-01-17 18:08:06 +00001269 if (isa<ZExtInst>(Op0LHS))
Craig Topperbb4069e2017-07-07 23:16:26 +00001270 BinOp = Builder.CreateBinOp(Op0I->getOpcode(), X, TruncC1);
David Majnemerde55c602017-01-17 18:08:06 +00001271 else
Craig Topperbb4069e2017-07-07 23:16:26 +00001272 BinOp = Builder.CreateBinOp(Op0I->getOpcode(), TruncC1, X);
David Majnemerde55c602017-01-17 18:08:06 +00001273 auto *TruncC2 = ConstantExpr::getTrunc(AndRHS, X->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001274 auto *And = Builder.CreateAnd(BinOp, TruncC2);
David Majnemerde55c602017-01-17 18:08:06 +00001275 return new ZExtInst(And, I.getType());
1276 }
1277 }
1278 }
1279
Chris Lattner0a8191e2010-01-05 07:50:36 +00001280 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1281 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1282 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001283 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001284
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001285 // If this is an integer truncation, and if the source is an 'and' with
1286 // immediate, transform it. This frequently occurs for bitfield accesses.
1287 {
Craig Topperf40110f2014-04-25 05:29:35 +00001288 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001289 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1290 // Change: and (trunc (and X, YC) to T), C2
1291 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001292 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001293 // other simplifications.
Craig Topperbb4069e2017-07-07 23:16:26 +00001294 Value *NewCast = Builder.CreateTrunc(X, I.getType(), "and.shrunk");
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001295 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1296 C3 = ConstantExpr::getAnd(C3, AndRHS);
1297 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001298 }
1299 }
Craig Topper86173602017-04-04 20:26:25 +00001300 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001301
Craig Topper86173602017-04-04 20:26:25 +00001302 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001303 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1304 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001305
Craig Topperbb4069e2017-07-07 23:16:26 +00001306 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001307 return DeMorgan;
Craig Topper9d4171a2012-12-20 07:09:41 +00001308
Chris Lattner0a8191e2010-01-05 07:50:36 +00001309 {
Sanjay Patele0c26e02017-04-23 22:00:02 +00001310 Value *A = nullptr, *B = nullptr, *C = nullptr;
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001311 // A&(A^B) => A & ~B
1312 {
1313 Value *tmpOp0 = Op0;
1314 Value *tmpOp1 = Op1;
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001315 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001316 if (A == Op1 || B == Op1 ) {
1317 tmpOp1 = Op0;
1318 tmpOp0 = Op1;
1319 // Simplify below
1320 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001321 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001322
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001323 if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001324 if (B == tmpOp0) {
1325 std::swap(A, B);
1326 }
Sanjay Pateld09b44a2016-01-18 17:50:23 +00001327 // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001328 // A is originally -1 (or a vector of -1 and undefs), then we enter
1329 // an endless loop. By checking that A is non-constant we ensure that
1330 // we will never get to the loop.
1331 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Craig Topperbb4069e2017-07-07 23:16:26 +00001332 return BinaryOperator::CreateAnd(A, Builder.CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001333 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001334 }
1335
David Majnemer42af3602014-07-30 21:26:37 +00001336 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1337 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1338 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001339 if (Op1->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
Craig Topperbb4069e2017-07-07 23:16:26 +00001340 return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(C));
David Majnemer42af3602014-07-30 21:26:37 +00001341
1342 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1343 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1344 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001345 if (Op0->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
Craig Topperbb4069e2017-07-07 23:16:26 +00001346 return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001347
1348 // (A | B) & ((~A) ^ B) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001349 // (A | B) & (B ^ (~A)) -> (A & B)
1350 // (B | A) & ((~A) ^ B) -> (A & B)
1351 // (B | A) & (B ^ (~A)) -> (A & B)
1352 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1353 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001354 return BinaryOperator::CreateAnd(A, B);
1355
1356 // ((~A) ^ B) & (A | B) -> (A & B)
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001357 // ((~A) ^ B) & (B | A) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001358 // (B ^ (~A)) & (A | B) -> (A & B)
1359 // (B ^ (~A)) & (B | A) -> (A & B)
1360 if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001361 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001362 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001363 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001364
David Majnemer5e96f1b2014-08-30 06:18:20 +00001365 {
1366 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1367 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1368 if (LHS && RHS)
Craig Topperda6ea0d2017-06-16 05:10:37 +00001369 if (Value *Res = foldAndOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001370 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001371
David Majnemer5e96f1b2014-08-30 06:18:20 +00001372 // TODO: Make this recursive; it's a little tricky because an arbitrary
1373 // number of 'and' instructions might have to be created.
1374 Value *X, *Y;
1375 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1376 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001377 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001378 return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001379 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001380 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001381 return replaceInstUsesWith(I, Builder.CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001382 }
1383 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1384 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001385 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001386 return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001387 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001388 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001389 return replaceInstUsesWith(I, Builder.CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001390 }
1391 }
1392
Chris Lattner4e8137d2010-02-11 06:26:33 +00001393 // If and'ing two fcmp, try combine them into one.
1394 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1395 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel5e456b92017-05-18 20:53:16 +00001396 if (Value *Res = foldAndOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001397 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001398
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001399 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1400 return CastedAnd;
Craig Topper9d4171a2012-12-20 07:09:41 +00001401
Craig Topper760ff6e2017-08-04 16:07:20 +00001402 // and(sext(A), B) / and(B, sext(A)) --> A ? B : 0, where A is i1 or <N x i1>.
1403 Value *A;
1404 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
1405 A->getType()->isIntOrIntVectorTy(1))
1406 return SelectInst::Create(A, Op1, Constant::getNullValue(I.getType()));
1407 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
1408 A->getType()->isIntOrIntVectorTy(1))
1409 return SelectInst::Create(A, Op0, Constant::getNullValue(I.getType()));
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001410
Craig Topperf40110f2014-04-25 05:29:35 +00001411 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001412}
1413
Chad Rosiera00df492016-05-25 16:22:14 +00001414/// Given an OR instruction, check to see if this is a bswap idiom. If so,
1415/// insert the new intrinsic and return it.
1416Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chad Rosiere5819e22016-05-26 14:58:51 +00001417 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1418
1419 // Look through zero extends.
1420 if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1421 Op0 = Ext->getOperand(0);
1422
1423 if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1424 Op1 = Ext->getOperand(0);
1425
1426 // (A | B) | C and A | (B | C) -> bswap if possible.
1427 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1428 match(Op1, m_Or(m_Value(), m_Value()));
1429
1430 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1431 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1432 match(Op1, m_LogicalShift(m_Value(), m_Value()));
1433
1434 // (A & B) | (C & D) -> bswap if possible.
1435 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1436 match(Op1, m_And(m_Value(), m_Value()));
1437
1438 if (!OrOfOrs && !OrOfShifts && !OrOfAnds)
1439 return nullptr;
1440
James Molloyf01488e2016-01-15 09:20:19 +00001441 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00001442 if (!recognizeBSwapOrBitReverseIdiom(&I, true, false, Insts))
Craig Topperf40110f2014-04-25 05:29:35 +00001443 return nullptr;
James Molloyf01488e2016-01-15 09:20:19 +00001444 Instruction *LastInst = Insts.pop_back_val();
1445 LastInst->removeFromParent();
Craig Topper9d4171a2012-12-20 07:09:41 +00001446
James Molloyf01488e2016-01-15 09:20:19 +00001447 for (auto *Inst : Insts)
1448 Worklist.Add(Inst);
1449 return LastInst;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001450}
1451
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001452/// If all elements of two constant vectors are 0/-1 and inverses, return true.
1453static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
1454 unsigned NumElts = C1->getType()->getVectorNumElements();
1455 for (unsigned i = 0; i != NumElts; ++i) {
1456 Constant *EltC1 = C1->getAggregateElement(i);
1457 Constant *EltC2 = C2->getAggregateElement(i);
1458 if (!EltC1 || !EltC2)
1459 return false;
1460
1461 // One element must be all ones, and the other must be all zeros.
1462 // FIXME: Allow undef elements.
1463 if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
1464 (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
1465 return false;
1466 }
1467 return true;
1468}
1469
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001470/// We have an expression of the form (A & C) | (B & D). If A is a scalar or
1471/// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
1472/// B, it can be used as the condition operand of a select instruction.
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001473static Value *getSelectCondition(Value *A, Value *B,
1474 InstCombiner::BuilderTy &Builder) {
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001475 // If these are scalars or vectors of i1, A can be used directly.
1476 Type *Ty = A->getType();
Craig Topperfde47232017-07-09 07:04:03 +00001477 if (match(A, m_Not(m_Specific(B))) && Ty->isIntOrIntVectorTy(1))
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001478 return A;
1479
1480 // If A and B are sign-extended, look through the sexts to find the booleans.
1481 Value *Cond;
Sanjay Pateld1e81192017-06-22 15:46:54 +00001482 Value *NotB;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001483 if (match(A, m_SExt(m_Value(Cond))) &&
Craig Topperfde47232017-07-09 07:04:03 +00001484 Cond->getType()->isIntOrIntVectorTy(1) &&
Sanjay Pateld1e81192017-06-22 15:46:54 +00001485 match(B, m_OneUse(m_Not(m_Value(NotB))))) {
1486 NotB = peekThroughBitcast(NotB, true);
1487 if (match(NotB, m_SExt(m_Specific(Cond))))
1488 return Cond;
1489 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001490
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001491 // All scalar (and most vector) possibilities should be handled now.
1492 // Try more matches that only apply to non-splat constant vectors.
1493 if (!Ty->isVectorTy())
1494 return nullptr;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001495
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001496 // If both operands are constants, see if the constants are inverse bitmasks.
1497 Constant *AC, *BC;
1498 if (match(A, m_Constant(AC)) && match(B, m_Constant(BC)) &&
1499 areInverseVectorBitmasks(AC, BC))
1500 return ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1501
1502 // If both operands are xor'd with constants using the same sexted boolean
1503 // operand, see if the constants are inverse bitmasks.
1504 if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AC)))) &&
1505 match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BC)))) &&
Craig Topperfde47232017-07-09 07:04:03 +00001506 Cond->getType()->isIntOrIntVectorTy(1) &&
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001507 areInverseVectorBitmasks(AC, BC)) {
1508 AC = ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1509 return Builder.CreateXor(Cond, AC);
1510 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001511 return nullptr;
1512}
1513
1514/// We have an expression of the form (A & C) | (B & D). Try to simplify this
1515/// to "A' ? C : D", where A' is a boolean or vector of booleans.
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001516static Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D,
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001517 InstCombiner::BuilderTy &Builder) {
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001518 // The potential condition of the select may be bitcasted. In that case, look
1519 // through its bitcast and the corresponding bitcast of the 'not' condition.
1520 Type *OrigType = A->getType();
Sanjay Patele800df8e2017-06-22 15:28:01 +00001521 A = peekThroughBitcast(A, true);
1522 B = peekThroughBitcast(B, true);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001523
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001524 if (Value *Cond = getSelectCondition(A, B, Builder)) {
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001525 // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001526 // The bitcasts will either all exist or all not exist. The builder will
1527 // not create unnecessary casts if the types already match.
1528 Value *BitcastC = Builder.CreateBitCast(C, A->getType());
1529 Value *BitcastD = Builder.CreateBitCast(D, A->getType());
1530 Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
1531 return Builder.CreateBitCast(Select, OrigType);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001532 }
Sanjay Patel5c0bc022016-06-02 18:03:05 +00001533
Craig Topperf40110f2014-04-25 05:29:35 +00001534 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001535}
1536
Sanjay Patel18549272015-09-08 18:24:36 +00001537/// Fold (icmp)|(icmp) if possible.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001538Value *InstCombiner::foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001539 Instruction &CxtI) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001540 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1541 // if K1 and K2 are a one-bit mask.
Craig Topperda6ea0d2017-06-16 05:10:37 +00001542 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, false, CxtI))
1543 return V;
1544
1545 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1546
Sanjay Patel519a87a2017-04-05 17:38:34 +00001547 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
1548 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001549
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001550 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1551 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1552 // The original condition actually refers to the following two ranges:
1553 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1554 // We can fold these two ranges if:
1555 // 1) C1 and C2 is unsigned greater than C3.
1556 // 2) The two ranges are separated.
1557 // 3) C1 ^ C2 is one-bit mask.
1558 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1559 // This implies all values in the two ranges differ by exactly one bit.
1560
Sanjay Patel519a87a2017-04-05 17:38:34 +00001561 if ((PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) &&
1562 PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() &&
1563 LHSC->getType() == RHSC->getType() &&
1564 LHSC->getValue() == (RHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001565
1566 Value *LAdd = LHS->getOperand(0);
1567 Value *RAdd = RHS->getOperand(0);
1568
1569 Value *LAddOpnd, *RAddOpnd;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001570 ConstantInt *LAddC, *RAddC;
1571 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddC))) &&
1572 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddC))) &&
1573 LAddC->getValue().ugt(LHSC->getValue()) &&
1574 RAddC->getValue().ugt(LHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001575
Sanjay Patel519a87a2017-04-05 17:38:34 +00001576 APInt DiffC = LAddC->getValue() ^ RAddC->getValue();
1577 if (LAddOpnd == RAddOpnd && DiffC.isPowerOf2()) {
1578 ConstantInt *MaxAddC = nullptr;
1579 if (LAddC->getValue().ult(RAddC->getValue()))
1580 MaxAddC = RAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001581 else
Sanjay Patel519a87a2017-04-05 17:38:34 +00001582 MaxAddC = LAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001583
Sanjay Patel519a87a2017-04-05 17:38:34 +00001584 APInt RRangeLow = -RAddC->getValue();
1585 APInt RRangeHigh = RRangeLow + LHSC->getValue();
1586 APInt LRangeLow = -LAddC->getValue();
1587 APInt LRangeHigh = LRangeLow + LHSC->getValue();
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001588 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1589 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1590 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1591 : RRangeLow - LRangeLow;
1592
1593 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
Sanjay Patel519a87a2017-04-05 17:38:34 +00001594 RangeDiff.ugt(LHSC->getValue())) {
1595 Value *MaskC = ConstantInt::get(LAddC->getType(), ~DiffC);
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001596
Craig Topperbb4069e2017-07-07 23:16:26 +00001597 Value *NewAnd = Builder.CreateAnd(LAddOpnd, MaskC);
1598 Value *NewAdd = Builder.CreateAdd(NewAnd, MaxAddC);
1599 return Builder.CreateICmp(LHS->getPredicate(), NewAdd, LHSC);
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001600 }
1601 }
1602 }
1603 }
1604
Chris Lattner0a8191e2010-01-05 07:50:36 +00001605 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001606 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001607 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1608 LHS->getOperand(1) == RHS->getOperand(0))
1609 LHS->swapOperands();
1610 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1611 LHS->getOperand(1) == RHS->getOperand(1)) {
1612 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1613 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1614 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001615 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001616 }
1617 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001618
1619 // handle (roughly):
1620 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001621 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001622 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001623
Sanjay Patele4159d22017-04-10 19:38:36 +00001624 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001625 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1626 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1627 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001628 Value *A = nullptr, *B = nullptr;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001629 if (PredL == ICmpInst::ICMP_EQ && LHSC && LHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001630 B = LHS0;
1631 if (PredR == ICmpInst::ICMP_ULT && LHS0 == RHS->getOperand(1))
1632 A = RHS0;
1633 else if (PredR == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001634 A = RHS->getOperand(1);
1635 }
1636 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1637 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001638 else if (PredR == ICmpInst::ICMP_EQ && RHSC && RHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001639 B = RHS0;
1640 if (PredL == ICmpInst::ICMP_ULT && RHS0 == LHS->getOperand(1))
1641 A = LHS0;
1642 else if (PredL == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001643 A = LHS->getOperand(1);
1644 }
1645 if (A && B)
Craig Topperbb4069e2017-07-07 23:16:26 +00001646 return Builder.CreateICmp(
David Majnemerc2a990b2013-07-05 00:31:17 +00001647 ICmpInst::ICMP_UGE,
Craig Topperbb4069e2017-07-07 23:16:26 +00001648 Builder.CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
David Majnemerc2a990b2013-07-05 00:31:17 +00001649 }
1650
Erik Ecksteind1817522014-12-03 10:39:15 +00001651 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1652 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1653 return V;
1654
1655 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1656 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1657 return V;
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001658
Sanjay Patelef9f5862017-04-15 17:55:06 +00001659 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, false, Builder))
1660 return V;
1661
David Majnemerc2a990b2013-07-05 00:31:17 +00001662 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001663 if (!LHSC || !RHSC)
1664 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001665
Sanjay Patel519a87a2017-04-05 17:38:34 +00001666 if (LHSC == RHSC && PredL == PredR) {
Owen Anderson8f306a72010-08-02 09:32:13 +00001667 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001668 if (PredL == ICmpInst::ICMP_NE && LHSC->isZero()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001669 Value *NewOr = Builder.CreateOr(LHS0, RHS0);
1670 return Builder.CreateICmp(PredL, NewOr, LHSC);
Owen Anderson8f306a72010-08-02 09:32:13 +00001671 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001672 }
1673
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001674 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001675 // iff C2 + CA == C1.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001676 if (PredL == ICmpInst::ICMP_ULT && PredR == ICmpInst::ICMP_EQ) {
1677 ConstantInt *AddC;
Sanjay Patele4159d22017-04-10 19:38:36 +00001678 if (match(LHS0, m_Add(m_Specific(RHS0), m_ConstantInt(AddC))))
Sanjay Patel519a87a2017-04-05 17:38:34 +00001679 if (RHSC->getValue() + AddC->getValue() == LHSC->getValue())
Craig Topperbb4069e2017-07-07 23:16:26 +00001680 return Builder.CreateICmpULE(LHS0, LHSC);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001681 }
1682
Chris Lattner0a8191e2010-01-05 07:50:36 +00001683 // From here on, we only handle:
1684 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +00001685 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001686 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001687
Sanjay Patel519a87a2017-04-05 17:38:34 +00001688 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
1689 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
1690 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
1691 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
1692 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001693 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001694
Chris Lattner0a8191e2010-01-05 07:50:36 +00001695 // We can't fold (ugt x, C) | (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001696 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +00001697 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001698
Chris Lattner0a8191e2010-01-05 07:50:36 +00001699 // Ensure that the larger constant is on the RHS.
1700 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +00001701 if (CmpInst::isSigned(PredL) ||
1702 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +00001703 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +00001704 else
1705 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001706
Chris Lattner0a8191e2010-01-05 07:50:36 +00001707 if (ShouldSwap) {
1708 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001709 std::swap(LHSC, RHSC);
1710 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001711 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001712
Dan Gohman4a618822010-02-10 16:03:48 +00001713 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001714 // comparing a value against two constants and or'ing the result
1715 // together. Because of the above check, we know that we only have
1716 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1717 // icmp folding check above), that the two constants are not
1718 // equal.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001719 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001720
Sanjay Patel519a87a2017-04-05 17:38:34 +00001721 switch (PredL) {
1722 default:
1723 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001724 case ICmpInst::ICMP_EQ:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001725 switch (PredR) {
1726 default:
1727 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001728 case ICmpInst::ICMP_EQ:
Sanjay Patel7cfe4162017-04-14 19:23:50 +00001729 // Potential folds for this case should already be handled.
1730 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001731 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1732 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001733 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001734 }
1735 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001736 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001737 switch (PredR) {
1738 default:
1739 llvm_unreachable("Unknown integer condition code!");
1740 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001741 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001742 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001743 assert(!RHSC->isMaxValue(false) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001744 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1,
1745 false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001746 }
1747 break;
1748 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001749 switch (PredR) {
1750 default:
1751 llvm_unreachable("Unknown integer condition code!");
1752 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001753 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001754 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001755 assert(!RHSC->isMaxValue(true) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001756 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1, true,
Sanjay Patel519a87a2017-04-05 17:38:34 +00001757 false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001758 }
1759 break;
1760 }
Craig Topperf40110f2014-04-25 05:29:35 +00001761 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001762}
1763
Sanjay Patel18549272015-09-08 18:24:36 +00001764/// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
1765/// a Value which should already be inserted into the function.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001766Value *InstCombiner::foldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +00001767 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1768 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1769 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1770
1771 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1772 // Swap RHS operands to match LHS.
1773 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1774 std::swap(Op1LHS, Op1RHS);
1775 }
1776
1777 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1778 // This is a similar transformation to the one in FoldAndOfFCmps.
1779 //
1780 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1781 // bool(R & CC0) || bool(R & CC1)
1782 // = bool((R & CC0) | (R & CC1))
1783 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1784 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1785 return getFCmpValue(getFCmpCode(Op0CC) | getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1786 Builder);
1787
Chris Lattner0a8191e2010-01-05 07:50:36 +00001788 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00001789 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001790 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1791 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1792 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1793 // If either of the constants are nans, then the whole thing returns
1794 // true.
1795 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Craig Topperbb4069e2017-07-07 23:16:26 +00001796 return Builder.getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001797
Chris Lattner0a8191e2010-01-05 07:50:36 +00001798 // Otherwise, no need to compare the two constants, compare the
1799 // rest.
Craig Topperbb4069e2017-07-07 23:16:26 +00001800 return Builder.CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001801 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001802
Chris Lattner0a8191e2010-01-05 07:50:36 +00001803 // Handle vector zeros. This occurs because the canonical form of
1804 // "fcmp uno x,x" is "fcmp uno x, 0".
1805 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1806 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Craig Topperbb4069e2017-07-07 23:16:26 +00001807 return Builder.CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00001808
Craig Topperf40110f2014-04-25 05:29:35 +00001809 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001810 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001811
Craig Topperf40110f2014-04-25 05:29:35 +00001812 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001813}
1814
Sanjay Patel18549272015-09-08 18:24:36 +00001815/// This helper function folds:
Chris Lattner0a8191e2010-01-05 07:50:36 +00001816///
1817/// ((A | B) & C1) | (B & C2)
1818///
1819/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00001820///
Chris Lattner0a8191e2010-01-05 07:50:36 +00001821/// (A & C1) | B
1822///
1823/// when the XOR of the two constants is "all ones" (-1).
Craig Toppera074c102017-06-21 18:57:00 +00001824static Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
1825 Value *A, Value *B, Value *C,
Craig Topperbb4069e2017-07-07 23:16:26 +00001826 InstCombiner::BuilderTy &Builder) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001827 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +00001828 if (!CI1) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001829
Craig Topperf40110f2014-04-25 05:29:35 +00001830 Value *V1 = nullptr;
1831 ConstantInt *CI2 = nullptr;
1832 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001833
1834 APInt Xor = CI1->getValue() ^ CI2->getValue();
Craig Topperf40110f2014-04-25 05:29:35 +00001835 if (!Xor.isAllOnesValue()) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001836
1837 if (V1 == A || V1 == B) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001838 Value *NewOp = Builder.CreateAnd((V1 == A) ? B : A, CI1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001839 return BinaryOperator::CreateOr(NewOp, V1);
1840 }
1841
Craig Topperf40110f2014-04-25 05:29:35 +00001842 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001843}
1844
David Majnemer5d1aeba2014-08-21 05:14:48 +00001845/// \brief This helper function folds:
1846///
Craig Toppera074c102017-06-21 18:57:00 +00001847/// ((A ^ B) & C1) | (B & C2)
David Majnemer5d1aeba2014-08-21 05:14:48 +00001848///
1849/// into:
1850///
1851/// (A & C1) ^ B
1852///
1853/// when the XOR of the two constants is "all ones" (-1).
Craig Toppera074c102017-06-21 18:57:00 +00001854static Instruction *FoldXorWithConstants(BinaryOperator &I, Value *Op,
1855 Value *A, Value *B, Value *C,
Craig Topperbb4069e2017-07-07 23:16:26 +00001856 InstCombiner::BuilderTy &Builder) {
David Majnemer5d1aeba2014-08-21 05:14:48 +00001857 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1858 if (!CI1)
1859 return nullptr;
1860
1861 Value *V1 = nullptr;
1862 ConstantInt *CI2 = nullptr;
1863 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
1864 return nullptr;
1865
1866 APInt Xor = CI1->getValue() ^ CI2->getValue();
1867 if (!Xor.isAllOnesValue())
1868 return nullptr;
1869
1870 if (V1 == A || V1 == B) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001871 Value *NewOp = Builder.CreateAnd(V1 == A ? B : A, CI1);
David Majnemer5d1aeba2014-08-21 05:14:48 +00001872 return BinaryOperator::CreateXor(NewOp, V1);
1873 }
1874
1875 return nullptr;
1876}
1877
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001878// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1879// here. We should standardize that construct where it is needed or choose some
1880// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001881Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001882 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001883 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1884
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001885 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001886 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001887
Craig Toppera4205622017-06-09 03:21:29 +00001888 if (Value *V = SimplifyOrInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001889 return replaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00001890
Craig Topper9d4171a2012-12-20 07:09:41 +00001891 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001892 // purpose is to compute bits we don't care about.
1893 if (SimplifyDemandedInstructionBits(I))
1894 return &I;
1895
Sanjay Patele0c26e02017-04-23 22:00:02 +00001896 // Do this before using distributive laws to catch simple and/or/not patterns.
Craig Topperbb4069e2017-07-07 23:16:26 +00001897 if (Instruction *Xor = foldOrToXor(I, Builder))
Sanjay Patele0c26e02017-04-23 22:00:02 +00001898 return Xor;
1899
1900 // (A&B)|(A&C) -> A&(B|C) etc
1901 if (Value *V = SimplifyUsingDistributiveLaws(I))
1902 return replaceInstUsesWith(I, V);
1903
Craig Topper95e41422017-07-06 16:24:23 +00001904 if (Value *V = SimplifyBSwap(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001905 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001906
Craig Topper86173602017-04-04 20:26:25 +00001907 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001908 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1909 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001910
Chad Rosiere5819e22016-05-26 14:58:51 +00001911 // Given an OR instruction, check to see if this is a bswap.
1912 if (Instruction *BSwap = MatchBSwap(I))
1913 return BSwap;
1914
Craig Topperafa07c52017-04-09 06:12:41 +00001915 {
1916 Value *A;
1917 const APInt *C;
1918 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1919 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
1920 MaskedValueIsZero(Op1, *C, 0, &I)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001921 Value *NOr = Builder.CreateOr(A, Op1);
Craig Topperafa07c52017-04-09 06:12:41 +00001922 NOr->takeName(Op0);
1923 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00001924 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00001925 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001926
Craig Topperafa07c52017-04-09 06:12:41 +00001927 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1928 if (match(Op1, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
1929 MaskedValueIsZero(Op0, *C, 0, &I)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001930 Value *NOr = Builder.CreateOr(A, Op0);
Craig Topperafa07c52017-04-09 06:12:41 +00001931 NOr->takeName(Op0);
1932 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00001933 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00001934 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001935 }
1936
Craig Topperafa07c52017-04-09 06:12:41 +00001937 Value *A, *B;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001938
1939 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00001940 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001941 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1942 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperf40110f2014-04-25 05:29:35 +00001943 Value *V1 = nullptr, *V2 = nullptr;
Craig Topperafa07c52017-04-09 06:12:41 +00001944 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1945 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001946 if (C1 && C2) { // (A & C1)|(B & C2)
Craig Topper73ba1c82017-06-07 07:40:37 +00001947 if ((C1->getValue() & C2->getValue()).isNullValue()) {
Chris Lattner95188692010-01-11 06:55:24 +00001948 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001949 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001950 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001951 ((V1 == B &&
1952 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
1953 (V2 == B &&
1954 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00001955 return BinaryOperator::CreateAnd(A,
Craig Topperbb4069e2017-07-07 23:16:26 +00001956 Builder.getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001957 // Or commutes, try both ways.
1958 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001959 ((V1 == A &&
1960 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
1961 (V2 == A &&
1962 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00001963 return BinaryOperator::CreateAnd(B,
Craig Topperbb4069e2017-07-07 23:16:26 +00001964 Builder.getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00001965
Chris Lattner95188692010-01-11 06:55:24 +00001966 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001967 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00001968 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00001969 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00001970 (C3->getValue() & ~C1->getValue()).isNullValue() &&
Chris Lattner95188692010-01-11 06:55:24 +00001971 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00001972 (C4->getValue() & ~C2->getValue()).isNullValue()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001973 V2 = Builder.CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
Chris Lattner95188692010-01-11 06:55:24 +00001974 return BinaryOperator::CreateAnd(V2,
Craig Topperbb4069e2017-07-07 23:16:26 +00001975 Builder.getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00001976 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001977 }
1978 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001979
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001980 // Don't try to form a select if it's unlikely that we'll get rid of at
1981 // least one of the operands. A select is generally more expensive than the
1982 // 'or' that it is replacing.
1983 if (Op0->hasOneUse() || Op1->hasOneUse()) {
1984 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
Craig Topperbb4069e2017-07-07 23:16:26 +00001985 if (Value *V = matchSelectFromAndOr(A, C, B, D, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001986 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001987 if (Value *V = matchSelectFromAndOr(A, C, D, B, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001988 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001989 if (Value *V = matchSelectFromAndOr(C, A, B, D, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001990 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001991 if (Value *V = matchSelectFromAndOr(C, A, D, B, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001992 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001993 if (Value *V = matchSelectFromAndOr(B, D, A, C, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001994 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001995 if (Value *V = matchSelectFromAndOr(B, D, C, A, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001996 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001997 if (Value *V = matchSelectFromAndOr(D, B, A, C, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001998 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001999 if (Value *V = matchSelectFromAndOr(D, B, C, A, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002000 return replaceInstUsesWith(I, V);
2001 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002002
Benjamin Kramer11743242010-07-12 13:34:22 +00002003 // ((A|B)&1)|(B&-2) -> (A&1) | B
Craig Toppera074c102017-06-21 18:57:00 +00002004 if (match(A, m_c_Or(m_Value(V1), m_Specific(B)))) {
2005 if (Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C, Builder))
2006 return Ret;
Benjamin Kramer11743242010-07-12 13:34:22 +00002007 }
2008 // (B&-2)|((A|B)&1) -> (A&1) | B
Craig Toppera074c102017-06-21 18:57:00 +00002009 if (match(B, m_c_Or(m_Specific(A), m_Value(V1)))) {
2010 if (Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D, Builder))
2011 return Ret;
Benjamin Kramer11743242010-07-12 13:34:22 +00002012 }
David Majnemer5d1aeba2014-08-21 05:14:48 +00002013 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
Craig Toppera074c102017-06-21 18:57:00 +00002014 if (match(A, m_c_Xor(m_Value(V1), m_Specific(B)))) {
2015 if (Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C, Builder))
2016 return Ret;
David Majnemer5d1aeba2014-08-21 05:14:48 +00002017 }
2018 // (B&-2)|((A^B)&1) -> (A&1) ^ B
Craig Toppera074c102017-06-21 18:57:00 +00002019 if (match(B, m_c_Xor(m_Specific(A), m_Value(V1)))) {
2020 if (Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D, Builder))
2021 return Ret;
David Majnemer5d1aeba2014-08-21 05:14:48 +00002022 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002023 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002024
David Majnemer42af3602014-07-30 21:26:37 +00002025 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2026 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2027 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00002028 return BinaryOperator::CreateOr(Op0, C);
David Majnemer42af3602014-07-30 21:26:37 +00002029
2030 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2031 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2032 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00002033 return BinaryOperator::CreateOr(Op1, C);
David Majnemer42af3602014-07-30 21:26:37 +00002034
David Majnemerf1eda232014-08-14 06:41:38 +00002035 // ((B | C) & A) | B -> B | (A & C)
2036 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
Craig Topperbb4069e2017-07-07 23:16:26 +00002037 return BinaryOperator::CreateOr(Op1, Builder.CreateAnd(A, C));
David Majnemerf1eda232014-08-14 06:41:38 +00002038
Craig Topperbb4069e2017-07-07 23:16:26 +00002039 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00002040 return DeMorgan;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002041
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002042 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002043 bool SwappedForXor = false;
2044 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002045 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002046 SwappedForXor = true;
2047 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002048
2049 // A | ( A ^ B) -> A | B
2050 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002051 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002052 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2053 if (Op0 == A || Op0 == B)
2054 return BinaryOperator::CreateOr(A, B);
2055
Chad Rosier7813dce2012-04-26 23:29:14 +00002056 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2057 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2058 return BinaryOperator::CreateOr(A, B);
2059
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002060 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002061 Value *Not = Builder.CreateNot(B, B->getName() + ".not");
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002062 return BinaryOperator::CreateOr(Not, Op0);
2063 }
2064 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002065 Value *Not = Builder.CreateNot(A, A->getName() + ".not");
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002066 return BinaryOperator::CreateOr(Not, Op0);
2067 }
2068 }
2069
2070 // A | ~(A | B) -> A | ~B
2071 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002072 if (match(Op1, m_Not(m_Value(A))))
2073 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002074 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2075 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2076 B->getOpcode() == Instruction::Xor)) {
2077 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2078 B->getOperand(0);
Craig Topperbb4069e2017-07-07 23:16:26 +00002079 Value *Not = Builder.CreateNot(NotOp, NotOp->getName() + ".not");
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002080 return BinaryOperator::CreateOr(Not, Op0);
2081 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002082
Eli Friedmane06535b2012-03-16 00:52:42 +00002083 if (SwappedForXor)
2084 std::swap(Op0, Op1);
2085
David Majnemer3d6f80b2014-11-28 19:58:29 +00002086 {
2087 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2088 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2089 if (LHS && RHS)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002090 if (Value *Res = foldOrOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002091 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002092
David Majnemer3d6f80b2014-11-28 19:58:29 +00002093 // TODO: Make this recursive; it's a little tricky because an arbitrary
2094 // number of 'or' instructions might have to be created.
2095 Value *X, *Y;
2096 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2097 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002098 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00002099 return replaceInstUsesWith(I, Builder.CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002100 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002101 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00002102 return replaceInstUsesWith(I, Builder.CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002103 }
2104 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2105 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002106 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00002107 return replaceInstUsesWith(I, Builder.CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002108 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002109 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00002110 return replaceInstUsesWith(I, Builder.CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002111 }
2112 }
2113
Chris Lattner4e8137d2010-02-11 06:26:33 +00002114 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2115 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2116 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel5e456b92017-05-18 20:53:16 +00002117 if (Value *Res = foldOrOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00002118 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002119
Sanjay Patel75b4ae22016-02-23 23:56:23 +00002120 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2121 return CastedOr;
Eli Friedman23956262011-04-14 22:41:27 +00002122
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002123 // or(sext(A), B) / or(B, sext(A)) --> A ? -1 : B, where A is i1 or <N x i1>.
Sanjay Patel1b6b8242016-07-08 17:26:47 +00002124 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
Craig Topperfde47232017-07-09 07:04:03 +00002125 A->getType()->isIntOrIntVectorTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002126 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
Sanjay Patel1b6b8242016-07-08 17:26:47 +00002127 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
Craig Topperfde47232017-07-09 07:04:03 +00002128 A->getType()->isIntOrIntVectorTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002129 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2130
Owen Andersonc237a842010-09-13 17:59:27 +00002131 // Note: If we've gotten to the point of visiting the outer OR, then the
2132 // inner one couldn't be simplified. If it was a constant, then it won't
2133 // be simplified by a later pass either, so we try swapping the inner/outer
2134 // ORs in the hopes that we'll be able to simplify it this way.
2135 // (X|C) | V --> (X|V) | C
Craig Topperafa07c52017-04-09 06:12:41 +00002136 ConstantInt *C1;
Owen Andersonc237a842010-09-13 17:59:27 +00002137 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2138 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002139 Value *Inner = Builder.CreateOr(A, Op1);
Owen Andersonc237a842010-09-13 17:59:27 +00002140 Inner->takeName(Op0);
2141 return BinaryOperator::CreateOr(Inner, C1);
2142 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002143
Bill Wendling23242092013-02-16 23:41:36 +00002144 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2145 // Since this OR statement hasn't been optimized further yet, we hope
2146 // that this transformation will allow the new ORs to be optimized.
2147 {
Craig Topperf40110f2014-04-25 05:29:35 +00002148 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002149 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2150 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2151 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002152 Value *orTrue = Builder.CreateOr(A, C);
2153 Value *orFalse = Builder.CreateOr(B, D);
Bill Wendling23242092013-02-16 23:41:36 +00002154 return SelectInst::Create(X, orTrue, orFalse);
2155 }
2156 }
2157
Craig Topperf40110f2014-04-25 05:29:35 +00002158 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002159}
2160
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002161/// A ^ B can be specified using other logic ops in a variety of patterns. We
2162/// can fold these early and efficiently by morphing an existing instruction.
Craig Topperf60ab472017-07-02 01:15:51 +00002163static Instruction *foldXorToXor(BinaryOperator &I,
2164 InstCombiner::BuilderTy &Builder) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002165 assert(I.getOpcode() == Instruction::Xor);
2166 Value *Op0 = I.getOperand(0);
2167 Value *Op1 = I.getOperand(1);
2168 Value *A, *B;
2169
2170 // There are 4 commuted variants for each of the basic patterns.
2171
2172 // (A & B) ^ (A | B) -> A ^ B
2173 // (A & B) ^ (B | A) -> A ^ B
2174 // (A | B) ^ (A & B) -> A ^ B
2175 // (A | B) ^ (B & A) -> A ^ B
2176 if ((match(Op0, m_And(m_Value(A), m_Value(B))) &&
2177 match(Op1, m_c_Or(m_Specific(A), m_Specific(B)))) ||
2178 (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2179 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))) {
2180 I.setOperand(0, A);
2181 I.setOperand(1, B);
2182 return &I;
2183 }
2184
2185 // (A | ~B) ^ (~A | B) -> A ^ B
2186 // (~B | A) ^ (~A | B) -> A ^ B
2187 // (~A | B) ^ (A | ~B) -> A ^ B
2188 // (B | ~A) ^ (A | ~B) -> A ^ B
Craig Topper880bf822017-06-30 07:37:41 +00002189 if ((match(Op0, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2190 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B)))) ||
2191 (match(Op0, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2192 match(Op1, m_c_Or(m_Specific(A), m_Not(m_Specific(B)))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002193 I.setOperand(0, A);
2194 I.setOperand(1, B);
2195 return &I;
2196 }
2197
2198 // (A & ~B) ^ (~A & B) -> A ^ B
2199 // (~B & A) ^ (~A & B) -> A ^ B
2200 // (~A & B) ^ (A & ~B) -> A ^ B
2201 // (B & ~A) ^ (A & ~B) -> A ^ B
Craig Topper880bf822017-06-30 07:37:41 +00002202 if ((match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2203 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))) ||
2204 (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2205 match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002206 I.setOperand(0, A);
2207 I.setOperand(1, B);
2208 return &I;
2209 }
2210
Craig Topperf60ab472017-07-02 01:15:51 +00002211 // For the remaining cases we need to get rid of one of the operands.
2212 if (!Op0->hasOneUse() && !Op1->hasOneUse())
2213 return nullptr;
2214
2215 // (A | B) ^ ~(A & B) -> ~(A ^ B)
2216 // (A | B) ^ ~(B & A) -> ~(A ^ B)
2217 // (A & B) ^ ~(A | B) -> ~(A ^ B)
2218 // (A & B) ^ ~(B | A) -> ~(A ^ B)
2219 // Complexity sorting ensures the not will be on the right side.
2220 if ((match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2221 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) ||
2222 (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2223 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))))
2224 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
2225
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002226 return nullptr;
2227}
2228
Sanjay Patel5e456b92017-05-18 20:53:16 +00002229Value *InstCombiner::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
2230 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2231 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2232 LHS->getOperand(1) == RHS->getOperand(0))
2233 LHS->swapOperands();
2234 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2235 LHS->getOperand(1) == RHS->getOperand(1)) {
2236 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2237 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2238 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2239 bool isSigned = LHS->isSigned() || RHS->isSigned();
2240 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
2241 }
2242 }
2243
Sanjay Pateladca8252017-06-20 12:40:55 +00002244 // Instead of trying to imitate the folds for and/or, decompose this 'xor'
2245 // into those logic ops. That is, try to turn this into an and-of-icmps
2246 // because we have many folds for that pattern.
2247 //
2248 // This is based on a truth table definition of xor:
2249 // X ^ Y --> (X | Y) & !(X & Y)
2250 if (Value *OrICmp = SimplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
2251 // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
2252 // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
2253 if (Value *AndICmp = SimplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
2254 // TODO: Independently handle cases where the 'and' side is a constant.
2255 if (OrICmp == LHS && AndICmp == RHS && RHS->hasOneUse()) {
2256 // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS
2257 RHS->setPredicate(RHS->getInversePredicate());
Craig Topperbb4069e2017-07-07 23:16:26 +00002258 return Builder.CreateAnd(LHS, RHS);
Sanjay Pateladca8252017-06-20 12:40:55 +00002259 }
2260 if (OrICmp == RHS && AndICmp == LHS && LHS->hasOneUse()) {
Sanjay Patel4ccbd582017-06-20 12:45:46 +00002261 // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS
Sanjay Pateladca8252017-06-20 12:40:55 +00002262 LHS->setPredicate(LHS->getInversePredicate());
Craig Topperbb4069e2017-07-07 23:16:26 +00002263 return Builder.CreateAnd(LHS, RHS);
Sanjay Pateladca8252017-06-20 12:40:55 +00002264 }
2265 }
2266 }
2267
Sanjay Patel5e456b92017-05-18 20:53:16 +00002268 return nullptr;
2269}
2270
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002271// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2272// here. We should standardize that construct where it is needed or choose some
2273// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002274Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002275 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002276 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2277
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002278 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002279 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002280
Craig Toppera4205622017-06-09 03:21:29 +00002281 if (Value *V = SimplifyXorInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002282 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002283
Craig Topperbb4069e2017-07-07 23:16:26 +00002284 if (Instruction *NewXor = foldXorToXor(I, Builder))
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002285 return NewXor;
2286
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002287 // (A&B)^(A&C) -> A&(B^C) etc
2288 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002289 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002290
Craig Topper9d4171a2012-12-20 07:09:41 +00002291 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002292 // purpose is to compute bits we don't care about.
2293 if (SimplifyDemandedInstructionBits(I))
2294 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002295
Craig Topper95e41422017-07-06 16:24:23 +00002296 if (Value *V = SimplifyBSwap(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002297 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002298
Sanjay Patel6381db12017-05-02 15:31:40 +00002299 // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
2300 Value *X, *Y;
2301
2302 // We must eliminate the and/or (one-use) for these transforms to not increase
2303 // the instruction count.
2304 // ~(~X & Y) --> (X | ~Y)
2305 // ~(Y & ~X) --> (X | ~Y)
2306 if (match(&I, m_Not(m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y)))))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002307 Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
Sanjay Patel6381db12017-05-02 15:31:40 +00002308 return BinaryOperator::CreateOr(X, NotY);
2309 }
2310 // ~(~X | Y) --> (X & ~Y)
2311 // ~(Y | ~X) --> (X & ~Y)
2312 if (match(&I, m_Not(m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y)))))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002313 Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
Sanjay Patel6381db12017-05-02 15:31:40 +00002314 return BinaryOperator::CreateAnd(X, NotY);
2315 }
2316
Sanjay Patel3b863f82017-04-22 18:05:35 +00002317 // Is this a 'not' (~) fed by a binary operator?
Sanjay Patela1c88142017-05-08 20:49:59 +00002318 BinaryOperator *NotVal;
2319 if (match(&I, m_Not(m_BinOp(NotVal)))) {
2320 if (NotVal->getOpcode() == Instruction::And ||
2321 NotVal->getOpcode() == Instruction::Or) {
Sanjay Patel6381db12017-05-02 15:31:40 +00002322 // Apply DeMorgan's Law when inverts are free:
2323 // ~(X & Y) --> (~X | ~Y)
2324 // ~(X | Y) --> (~X & ~Y)
Sanjay Patela1c88142017-05-08 20:49:59 +00002325 if (IsFreeToInvert(NotVal->getOperand(0),
2326 NotVal->getOperand(0)->hasOneUse()) &&
2327 IsFreeToInvert(NotVal->getOperand(1),
2328 NotVal->getOperand(1)->hasOneUse())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002329 Value *NotX = Builder.CreateNot(NotVal->getOperand(0), "notlhs");
2330 Value *NotY = Builder.CreateNot(NotVal->getOperand(1), "notrhs");
Sanjay Patela1c88142017-05-08 20:49:59 +00002331 if (NotVal->getOpcode() == Instruction::And)
Sanjay Patel3b863f82017-04-22 18:05:35 +00002332 return BinaryOperator::CreateOr(NotX, NotY);
2333 return BinaryOperator::CreateAnd(NotX, NotY);
2334 }
Sanjay Patela1c88142017-05-08 20:49:59 +00002335 }
2336
2337 // ~(~X >>s Y) --> (X >>s Y)
2338 if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
2339 return BinaryOperator::CreateAShr(X, Y);
2340
2341 // If we are inverting a right-shifted constant, we may be able to eliminate
2342 // the 'not' by inverting the constant and using the opposite shift type.
2343 // Canonicalization rules ensure that only a negative constant uses 'ashr',
2344 // but we must check that in case that transform has not fired yet.
2345 const APInt *C;
2346 if (match(NotVal, m_AShr(m_APInt(C), m_Value(Y))) && C->isNegative()) {
2347 // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
2348 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2349 return BinaryOperator::CreateLShr(NotC, Y);
2350 }
2351
2352 if (match(NotVal, m_LShr(m_APInt(C), m_Value(Y))) && C->isNonNegative()) {
2353 // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
2354 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2355 return BinaryOperator::CreateAShr(NotC, Y);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002356 }
2357 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002358
Craig Topper798a19a2017-06-29 00:07:08 +00002359 // not (cmp A, B) = !cmp A, B
Craig Toppercc418b62017-07-05 20:31:00 +00002360 CmpInst::Predicate Pred;
Craig Topper798a19a2017-06-29 00:07:08 +00002361 if (match(&I, m_Not(m_OneUse(m_Cmp(Pred, m_Value(), m_Value()))))) {
Sanjay Patel33439f92017-04-12 15:11:33 +00002362 cast<CmpInst>(Op0)->setPredicate(CmpInst::getInversePredicate(Pred));
2363 return replaceInstUsesWith(I, Op0);
Benjamin Kramer443c7962015-02-12 20:26:46 +00002364 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002365
Craig Topperb5bf0162017-08-06 06:28:41 +00002366 {
2367 const APInt *RHSC;
2368 if (match(Op1, m_APInt(RHSC))) {
2369 Value *V;
2370 const APInt *C;
2371 if (match(Op0, m_Sub(m_APInt(C), m_Value(V)))) {
2372 // ~(c-X) == X-c-1 == X+(-c-1)
2373 if (RHSC->isAllOnesValue()) {
2374 Constant *NewC = ConstantInt::get(I.getType(), -(*C) - 1);
2375 return BinaryOperator::CreateAdd(V, NewC);
2376 }
Craig Topper9cbdbef2017-08-06 22:17:21 +00002377 if (RHSC->isSignMask()) {
2378 // (C - X) ^ signmask -> (C + signmask - X)
2379 Constant *NewC = ConstantInt::get(I.getType(), *C + *RHSC);
2380 return BinaryOperator::CreateSub(NewC, V);
2381 }
Craig Topperb5bf0162017-08-06 06:28:41 +00002382 } else if (match(Op0, m_Add(m_Value(V), m_APInt(C)))) {
2383 // ~(X-c) --> (-c-1)-X
2384 if (RHSC->isAllOnesValue()) {
2385 Constant *NewC = ConstantInt::get(I.getType(), -(*C) - 1);
2386 return BinaryOperator::CreateSub(NewC, V);
2387 }
Craig Topper9cbdbef2017-08-06 22:17:21 +00002388 if (RHSC->isSignMask()) {
2389 // (X + C) ^ signmask -> (X + C + signmask)
2390 Constant *NewC = ConstantInt::get(I.getType(), *C + *RHSC);
2391 return BinaryOperator::CreateAdd(V, NewC);
2392 }
Craig Topperb5bf0162017-08-06 06:28:41 +00002393 }
2394 }
2395 }
2396
Craig Topper9d1821b2017-04-09 06:12:31 +00002397 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002398 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002399 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Craig Topper9cbdbef2017-08-06 22:17:21 +00002400 if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002401 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Hal Finkel60db0582014-09-07 18:57:58 +00002402 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2403 0, &I)) {
Craig Topper9d1821b2017-04-09 06:12:31 +00002404 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002405 // Anything in both C1 and C2 is known to be zero, remove it from
2406 // NewRHS.
Craig Topper9d1821b2017-04-09 06:12:31 +00002407 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHSC);
Craig Topper9d4171a2012-12-20 07:09:41 +00002408 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002409 ConstantExpr::getNot(CommonBits));
2410 Worklist.Add(Op0I);
2411 I.setOperand(0, Op0I->getOperand(0));
2412 I.setOperand(1, NewRHS);
2413 return &I;
2414 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002415 } else if (Op0I->getOpcode() == Instruction::LShr) {
2416 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2417 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002418 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002419 ConstantInt *C1;
2420 if (Op0I->hasOneUse() &&
2421 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2422 E1->getOpcode() == Instruction::Xor &&
2423 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2424 // fold (C1 >> C2) ^ C3
Craig Topper9d1821b2017-04-09 06:12:31 +00002425 ConstantInt *C2 = Op0CI, *C3 = RHSC;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002426 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2427 FoldConst ^= C3->getValue();
2428 // Prepare the two operands.
Craig Topperbb4069e2017-07-07 23:16:26 +00002429 Value *Opnd0 = Builder.CreateLShr(E1->getOperand(0), C2);
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002430 Opnd0->takeName(Op0I);
2431 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2432 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2433
2434 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2435 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002436 }
2437 }
2438 }
Craig Topper86173602017-04-04 20:26:25 +00002439 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002440
Craig Topper86173602017-04-04 20:26:25 +00002441 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00002442 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2443 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002444
Craig Topper76394602017-04-10 06:53:23 +00002445 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002446 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002447 if (match(Op1, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Craig Topper47383212017-04-10 06:53:21 +00002448 if (A == Op0) { // A^(A|B) == A^(B|A)
Craig Topper76394602017-04-10 06:53:23 +00002449 cast<BinaryOperator>(Op1)->swapOperands();
Craig Topper47383212017-04-10 06:53:21 +00002450 std::swap(A, B);
2451 }
2452 if (B == Op0) { // A^(B|A) == (B|A)^A
Chris Lattner0a8191e2010-01-05 07:50:36 +00002453 I.swapOperands(); // Simplified below.
2454 std::swap(Op0, Op1);
2455 }
Craig Topper76394602017-04-10 06:53:23 +00002456 } else if (match(Op1, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002457 if (A == Op0) { // A^(A&B) -> A^(B&A)
Craig Topper76394602017-04-10 06:53:23 +00002458 cast<BinaryOperator>(Op1)->swapOperands();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002459 std::swap(A, B);
2460 }
2461 if (B == Op0) { // A^(B&A) -> (B&A)^A
2462 I.swapOperands(); // Simplified below.
2463 std::swap(Op0, Op1);
2464 }
2465 }
2466 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002467
Craig Topper76394602017-04-10 06:53:23 +00002468 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002469 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002470 if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002471 if (A == Op1) // (B|A)^B == (A|B)^B
2472 std::swap(A, B);
2473 if (B == Op1) // (A|B)^B == A & ~B
Craig Topperbb4069e2017-07-07 23:16:26 +00002474 return BinaryOperator::CreateAnd(A, Builder.CreateNot(Op1));
Craig Topper76394602017-04-10 06:53:23 +00002475 } else if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002476 if (A == Op1) // (A&B)^A -> (B&A)^A
2477 std::swap(A, B);
Craig Toppere63c21b2017-04-09 06:12:39 +00002478 const APInt *C;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002479 if (B == Op1 && // (B&A)^A == ~B & A
Craig Toppere63c21b2017-04-09 06:12:39 +00002480 !match(Op1, m_APInt(C))) { // Canonical form is (B&C)^C
Craig Topperbb4069e2017-07-07 23:16:26 +00002481 return BinaryOperator::CreateAnd(Builder.CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002482 }
2483 }
2484 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002485
Craig Topper76394602017-04-10 06:53:23 +00002486 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002487 Value *A, *B, *C, *D;
David Majnemer6fe6ea72014-09-05 06:09:24 +00002488 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002489 if (match(Op0, m_Xor(m_Value(D), m_Value(C))) &&
2490 match(Op1, m_Or(m_Value(A), m_Value(B)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002491 if (D == A)
2492 return BinaryOperator::CreateXor(
Craig Topperbb4069e2017-07-07 23:16:26 +00002493 Builder.CreateAnd(Builder.CreateNot(A), B), C);
David Majnemer6fe6ea72014-09-05 06:09:24 +00002494 if (D == B)
2495 return BinaryOperator::CreateXor(
Craig Topperbb4069e2017-07-07 23:16:26 +00002496 Builder.CreateAnd(Builder.CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002497 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002498 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002499 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2500 match(Op1, m_Xor(m_Value(D), m_Value(C)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002501 if (D == A)
2502 return BinaryOperator::CreateXor(
Craig Topperbb4069e2017-07-07 23:16:26 +00002503 Builder.CreateAnd(Builder.CreateNot(A), B), C);
David Majnemer6fe6ea72014-09-05 06:09:24 +00002504 if (D == B)
2505 return BinaryOperator::CreateXor(
Craig Topperbb4069e2017-07-07 23:16:26 +00002506 Builder.CreateAnd(Builder.CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002507 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002508 // (A & B) ^ (A ^ B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002509 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002510 match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002511 return BinaryOperator::CreateOr(A, B);
2512 // (A ^ B) ^ (A & B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002513 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002514 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002515 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002516 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002517
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002518 // (A & ~B) ^ ~A -> ~(A & B)
2519 // (~B & A) ^ ~A -> ~(A & B)
2520 Value *A, *B;
2521 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
Suyog Sarda56c9a872014-08-01 05:07:20 +00002522 match(Op1, m_Not(m_Specific(A))))
Craig Topperbb4069e2017-07-07 23:16:26 +00002523 return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
Suyog Sarda56c9a872014-08-01 05:07:20 +00002524
Sanjay Patel5e456b92017-05-18 20:53:16 +00002525 if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2526 if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2527 if (Value *V = foldXorOfICmps(LHS, RHS))
2528 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002529
Sanjay Pateldbbaca02016-02-24 17:00:34 +00002530 if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2531 return CastedXor;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002532
Craig Topperf40110f2014-04-25 05:29:35 +00002533 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002534}