blob: fe9844365bf4c0b97fa46553c1991124f7e4fd2d [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,
57 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;
61 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,
Chris Lattner067459c2010-03-05 08:46: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);
Chris Lattner067459c2010-03-05 08:46:26 +000075 return Builder->CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000076}
77
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000078/// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) to BSWAP(BITWISE_OP(A, B))
79/// \param I Binary operator to transform.
80/// \return Pointer to node that must replace the original binary operator, or
81/// null pointer if no transformation was made.
82Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
83 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
84
85 // Can't do vectors.
Sanjay Patel1e6ca442016-11-22 22:54:36 +000086 if (I.getType()->isVectorTy())
87 return nullptr;
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000088
89 // Can only do bitwise ops.
Sanjay Patel1e6ca442016-11-22 22:54:36 +000090 if (!I.isBitwiseLogicOp())
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000091 return nullptr;
92
93 Value *OldLHS = I.getOperand(0);
94 Value *OldRHS = I.getOperand(1);
95 ConstantInt *ConstLHS = dyn_cast<ConstantInt>(OldLHS);
96 ConstantInt *ConstRHS = dyn_cast<ConstantInt>(OldRHS);
97 IntrinsicInst *IntrLHS = dyn_cast<IntrinsicInst>(OldLHS);
98 IntrinsicInst *IntrRHS = dyn_cast<IntrinsicInst>(OldRHS);
99 bool IsBswapLHS = (IntrLHS && IntrLHS->getIntrinsicID() == Intrinsic::bswap);
100 bool IsBswapRHS = (IntrRHS && IntrRHS->getIntrinsicID() == Intrinsic::bswap);
101
102 if (!IsBswapLHS && !IsBswapRHS)
103 return nullptr;
104
105 if (!IsBswapLHS && !ConstLHS)
106 return nullptr;
107
108 if (!IsBswapRHS && !ConstRHS)
109 return nullptr;
110
111 /// OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
112 /// OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
113 Value *NewLHS = IsBswapLHS ? IntrLHS->getOperand(0) :
114 Builder->getInt(ConstLHS->getValue().byteSwap());
115
116 Value *NewRHS = IsBswapRHS ? IntrRHS->getOperand(0) :
117 Builder->getInt(ConstRHS->getValue().byteSwap());
118
Sanjay Patel1e6ca442016-11-22 22:54:36 +0000119 Value *BinOp = Builder->CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000120 Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap, ITy);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000121 return Builder->CreateCall(F, BinOp);
122}
123
Sanjay Patel18549272015-09-08 18:24:36 +0000124/// This handles expressions of the form ((val OP C1) & C2). Where
Craig Topper70e4f432017-04-02 17:57:30 +0000125/// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.
126Instruction *InstCombiner::OptAndOp(BinaryOperator *Op,
Chris Lattner0a8191e2010-01-05 07:50:36 +0000127 ConstantInt *OpRHS,
128 ConstantInt *AndRHS,
129 BinaryOperator &TheAnd) {
130 Value *X = Op->getOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +0000131 Constant *Together = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000132 if (!Op->isShift())
133 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
134
135 switch (Op->getOpcode()) {
Craig Topper70e4f432017-04-02 17:57:30 +0000136 default: break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000137 case Instruction::Xor:
138 if (Op->hasOneUse()) {
139 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
140 Value *And = Builder->CreateAnd(X, AndRHS);
141 And->takeName(Op);
142 return BinaryOperator::CreateXor(And, Together);
143 }
144 break;
145 case Instruction::Or:
Owen Andersonc237a842010-09-13 17:59:27 +0000146 if (Op->hasOneUse()){
Owen Andersonc237a842010-09-13 17:59:27 +0000147 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
148 if (TogetherCI && !TogetherCI->isZero()){
149 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
150 // NOTE: This reduces the number of bits set in the & mask, which
151 // can expose opportunities for store narrowing.
152 Together = ConstantExpr::getXor(AndRHS, Together);
153 Value *And = Builder->CreateAnd(X, Together);
154 And->takeName(Op);
155 return BinaryOperator::CreateOr(And, OpRHS);
156 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000157 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000158
Chris Lattner0a8191e2010-01-05 07:50:36 +0000159 break;
160 case Instruction::Add:
161 if (Op->hasOneUse()) {
162 // Adding a one to a single bit bit-field should be turned into an XOR
163 // of the bit. First thing to check is to see if this AND is with a
164 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000165 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000166
167 // If there is only one bit set.
168 if (AndRHSV.isPowerOf2()) {
169 // Ok, at this point, we know that we are masking the result of the
170 // ADD down to exactly one bit. If the constant we are adding has
171 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000172 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000173
174 // Check to see if any bits below the one bit set in AndRHSV are set.
Craig Topper73ba1c82017-06-07 07:40:37 +0000175 if ((AddRHS & (AndRHSV - 1)).isNullValue()) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000176 // If not, the only thing that can effect the output of the AND is
177 // the bit specified by AndRHSV. If that bit is set, the effect of
178 // the XOR is to toggle the bit. If it is clear, then the ADD has
179 // no effect.
Craig Topper73ba1c82017-06-07 07:40:37 +0000180 if ((AddRHS & AndRHSV).isNullValue()) { // Bit is not set, noop
Chris Lattner0a8191e2010-01-05 07:50:36 +0000181 TheAnd.setOperand(0, X);
182 return &TheAnd;
183 } else {
184 // Pull the XOR out of the AND.
185 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
186 NewAnd->takeName(Op);
187 return BinaryOperator::CreateXor(NewAnd, AndRHS);
188 }
189 }
190 }
191 }
192 break;
193
194 case Instruction::Shl: {
195 // We know that the AND will not produce any of the bits shifted in, so if
196 // the anded constant includes them, clear them now!
197 //
198 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
199 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
200 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000201 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000202
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000203 if (CI->getValue() == ShlMask)
204 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000205 return replaceInstUsesWith(TheAnd, Op); // No need for the and.
Craig Topper9d4171a2012-12-20 07:09:41 +0000206
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000207 if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000208 TheAnd.setOperand(1, CI);
209 return &TheAnd;
210 }
211 break;
212 }
213 case Instruction::LShr: {
214 // We know that the AND will not produce any of the bits shifted in, so if
215 // the anded constant includes them, clear them now! This only applies to
216 // unsigned shifts, because a signed shr may bring in set bits!
217 //
218 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
219 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
220 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000221 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000222
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000223 if (CI->getValue() == ShrMask)
224 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000225 return replaceInstUsesWith(TheAnd, Op);
Craig Topper9d4171a2012-12-20 07:09:41 +0000226
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000227 if (CI != AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000228 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
229 return &TheAnd;
230 }
231 break;
232 }
233 case Instruction::AShr:
234 // Signed shr.
235 // See if this is shifting in some sign extension, then masking it out
236 // with an and.
237 if (Op->hasOneUse()) {
238 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
239 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
240 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000241 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000242 if (C == AndRHS) { // Masking out bits shifted in.
243 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
244 // Make the argument unsigned.
245 Value *ShVal = Op->getOperand(0);
246 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
247 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
248 }
249 }
250 break;
251 }
Craig Topperf40110f2014-04-25 05:29:35 +0000252 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000253}
254
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000255/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000256/// (V < Lo || V >= Hi). This method expects that Lo <= Hi. IsSigned indicates
257/// whether to treat V, Lo, and Hi as signed or not.
Sanjay Patel85d79742016-08-31 19:49:56 +0000258Value *InstCombiner::insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
Chris Lattner067459c2010-03-05 08:46:26 +0000259 bool isSigned, bool Inside) {
Sanjay Patel85d79742016-08-31 19:49:56 +0000260 assert((isSigned ? Lo.sle(Hi) : Lo.ule(Hi)) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000261 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000262
Sanjay Patel85d79742016-08-31 19:49:56 +0000263 Type *Ty = V->getType();
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000264 if (Lo == Hi)
Sanjay Patel85d79742016-08-31 19:49:56 +0000265 return Inside ? ConstantInt::getFalse(Ty) : ConstantInt::getTrue(Ty);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000266
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000267 // V >= Min && V < Hi --> V < Hi
268 // V < Min || V >= Hi --> V >= Hi
269 ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
Sanjay Patel85d79742016-08-31 19:49:56 +0000270 if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000271 Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
Sanjay Patel85d79742016-08-31 19:49:56 +0000272 return Builder->CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000273 }
274
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000275 // V >= Lo && V < Hi --> V - Lo u< Hi - Lo
276 // V < Lo || V >= Hi --> V - Lo u>= Hi - Lo
Sanjay Patel85d79742016-08-31 19:49:56 +0000277 Value *VMinusLo =
278 Builder->CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
279 Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000280 return Builder->CreateICmp(Pred, VMinusLo, HiMinusLo);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000281}
282
Sanjay Patel77bf6222017-04-03 16:53:12 +0000283/// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
284/// that can be simplified.
285/// One of A and B is considered the mask. The other is the value. This is
286/// described as the "AMask" or "BMask" part of the enum. If the enum contains
287/// only "Mask", then both A and B can be considered masks. If A is the mask,
288/// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
289/// If both A and C are constants, this proof is also easy.
290/// For the following explanations, we assume that A is the mask.
291///
292/// "AllOnes" declares that the comparison is true only if (A & B) == A or all
293/// bits of A are set in B.
294/// Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
295///
296/// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
297/// bits of A are cleared in B.
298/// Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
299///
300/// "Mixed" declares that (A & B) == C and C might or might not contain any
301/// number of one bits and zero bits.
302/// Example: (icmp eq (A & 3), 1) -> AMask_Mixed
303///
304/// "Not" means that in above descriptions "==" should be replaced by "!=".
305/// Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
306///
Owen Anderson3fe002d2010-09-08 22:16:17 +0000307/// If the mask A contains a single bit, then the following is equivalent:
308/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
309/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
310enum MaskedICmpType {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000311 AMask_AllOnes = 1,
312 AMask_NotAllOnes = 2,
313 BMask_AllOnes = 4,
314 BMask_NotAllOnes = 8,
315 Mask_AllZeros = 16,
316 Mask_NotAllZeros = 32,
317 AMask_Mixed = 64,
318 AMask_NotMixed = 128,
319 BMask_Mixed = 256,
320 BMask_NotMixed = 512
Owen Anderson3fe002d2010-09-08 22:16:17 +0000321};
322
Sanjay Patel77bf6222017-04-03 16:53:12 +0000323/// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
324/// satisfies.
325static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
326 ICmpInst::Predicate Pred) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000327 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
328 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
329 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000330 bool IsEq = (Pred == ICmpInst::ICMP_EQ);
331 bool IsAPow2 = (ACst && !ACst->isZero() && ACst->getValue().isPowerOf2());
332 bool IsBPow2 = (BCst && !BCst->isZero() && BCst->getValue().isPowerOf2());
333 unsigned MaskVal = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000334 if (CCst && CCst->isZero()) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000335 // if C is zero, then both A and B qualify as mask
Sanjay Patel77bf6222017-04-03 16:53:12 +0000336 MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
337 : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
338 if (IsAPow2)
339 MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
340 : (AMask_AllOnes | AMask_Mixed));
341 if (IsBPow2)
342 MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
343 : (BMask_AllOnes | BMask_Mixed));
344 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000345 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000346
Owen Anderson3fe002d2010-09-08 22:16:17 +0000347 if (A == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000348 MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
349 : (AMask_NotAllOnes | AMask_NotMixed));
350 if (IsAPow2)
351 MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
352 : (Mask_AllZeros | AMask_Mixed));
353 } else if (ACst && CCst && ConstantExpr::getAnd(ACst, CCst) == CCst) {
354 MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000355 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000356
Craig Topperae48cb22012-12-20 07:15:54 +0000357 if (B == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000358 MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
359 : (BMask_NotAllOnes | BMask_NotMixed));
360 if (IsBPow2)
361 MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
362 : (Mask_AllZeros | BMask_Mixed));
363 } else if (BCst && CCst && ConstantExpr::getAnd(BCst, CCst) == CCst) {
364 MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000365 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000366
367 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000368}
369
Tim Northoverc0756c42013-09-04 11:57:13 +0000370/// Convert an analysis of a masked ICmp into its equivalent if all boolean
371/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
372/// is adjacent to the corresponding normal flag (recording ==), this just
373/// involves swapping those bits over.
374static unsigned conjugateICmpMask(unsigned Mask) {
375 unsigned NewMask;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000376 NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
377 AMask_Mixed | BMask_Mixed))
Tim Northoverc0756c42013-09-04 11:57:13 +0000378 << 1;
379
Sanjay Patel77bf6222017-04-03 16:53:12 +0000380 NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
381 AMask_NotMixed | BMask_NotMixed))
382 >> 1;
Tim Northoverc0756c42013-09-04 11:57:13 +0000383
384 return NewMask;
385}
386
Sanjay Patel77bf6222017-04-03 16:53:12 +0000387/// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
388/// Return the set of pattern classes (from MaskedICmpType) that both LHS and
389/// RHS satisfy.
390static unsigned getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C,
391 Value *&D, Value *&E, ICmpInst *LHS,
392 ICmpInst *RHS,
393 ICmpInst::Predicate &PredL,
394 ICmpInst::Predicate &PredR) {
395 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
396 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000397 // vectors are not (yet?) supported
Sanjay Patel77bf6222017-04-03 16:53:12 +0000398 if (LHS->getOperand(0)->getType()->isVectorTy())
399 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000400
401 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000402 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000403 // and L11 & L12 == L21 & L22. The same goes for RHS.
404 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000405 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000406 // above.
407 Value *L1 = LHS->getOperand(0);
408 Value *L2 = LHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000409 Value *L11, *L12, *L21, *L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000410 // Check whether the icmp can be decomposed into a bit test.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000411 if (decomposeBitTestICmp(LHS, PredL, L11, L12, L2)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000412 L21 = L22 = L1 = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000413 } else {
414 // Look for ANDs in the LHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000415 if (!L1->getType()->isIntegerTy()) {
416 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000417 L11 = L12 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000418 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
419 // Any icmp can be viewed as being trivially masked; if it allows us to
420 // remove one, it's worth it.
421 L11 = L1;
422 L12 = Constant::getAllOnesValue(L1->getType());
423 }
424
425 if (!L2->getType()->isIntegerTy()) {
426 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000427 L21 = L22 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000428 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
429 L21 = L2;
430 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000431 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000432 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000433
434 // Bail if LHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000435 if (!ICmpInst::isEquality(PredL))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000436 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000437
438 Value *R1 = RHS->getOperand(0);
439 Value *R2 = RHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000440 Value *R11, *R12;
441 bool Ok = false;
442 if (decomposeBitTestICmp(RHS, PredR, R11, R12, R2)) {
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000443 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000444 A = R11;
445 D = R12;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000446 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000447 A = R12;
448 D = R11;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000449 } else {
450 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000451 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000452 E = R2;
453 R1 = nullptr;
454 Ok = true;
Tim Northoverdc647a22013-09-04 11:57:17 +0000455 } else if (R1->getType()->isIntegerTy()) {
456 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
457 // As before, model no mask as a trivial mask if it'll let us do an
Mayur Pandey75b76c62014-08-19 06:41:55 +0000458 // optimization.
Tim Northoverdc647a22013-09-04 11:57:17 +0000459 R11 = R1;
460 R12 = Constant::getAllOnesValue(R1->getType());
461 }
462
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000463 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000464 A = R11;
465 D = R12;
466 E = R2;
467 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000468 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000469 A = R12;
470 D = R11;
471 E = R2;
472 Ok = true;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000473 }
474 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000475
476 // Bail if RHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000477 if (!ICmpInst::isEquality(PredR))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000478 return 0;
479
Chad Rosier58919cc2016-05-09 21:37:43 +0000480 // Look for ANDs on the right side of the RHS icmp.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000481 if (!Ok && R2->getType()->isIntegerTy()) {
Tim Northoverdc647a22013-09-04 11:57:17 +0000482 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
483 R11 = R2;
484 R12 = Constant::getAllOnesValue(R2->getType());
485 }
486
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000487 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000488 A = R11;
489 D = R12;
490 E = R1;
491 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000492 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000493 A = R12;
494 D = R11;
495 E = R1;
496 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000497 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000498 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000499 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000500 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000501 if (!Ok)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000502 return 0;
503
504 if (L11 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000505 B = L12;
506 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000507 } else if (L12 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000508 B = L11;
509 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000510 } else if (L21 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000511 B = L22;
512 C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000513 } else if (L22 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000514 B = L21;
515 C = L1;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000516 }
517
Sanjay Patel77bf6222017-04-03 16:53:12 +0000518 unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
519 unsigned RightType = getMaskedICmpType(A, D, E, PredR);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000520 return LeftType & RightType;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000521}
Sanjay Patel18549272015-09-08 18:24:36 +0000522
523/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
524/// into a single (icmp(A & X) ==/!= Y).
David Majnemer1a3327b2014-11-18 09:31:36 +0000525static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
526 llvm::InstCombiner::BuilderTy *Builder) {
Craig Topperf40110f2014-04-25 05:29:35 +0000527 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000528 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
529 unsigned Mask =
530 getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
531 if (Mask == 0)
532 return nullptr;
533
534 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
535 "Expected equality predicates for masked type of icmps.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000536
Tim Northoverc0756c42013-09-04 11:57:13 +0000537 // In full generality:
538 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
539 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
540 //
541 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
542 // equivalent to (icmp (A & X) !Op Y).
543 //
544 // Therefore, we can pretend for the rest of this function that we're dealing
545 // with the conjunction, provided we flip the sense of any comparisons (both
546 // input and output).
547
548 // In most cases we're going to produce an EQ for the "&&" case.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000549 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Tim Northoverc0756c42013-09-04 11:57:13 +0000550 if (!IsAnd) {
551 // Convert the masking analysis into its equivalent with negated
552 // comparisons.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000553 Mask = conjugateICmpMask(Mask);
Tim Northoverc0756c42013-09-04 11:57:13 +0000554 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000555
Sanjay Patel77bf6222017-04-03 16:53:12 +0000556 if (Mask & Mask_AllZeros) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000557 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000558 // -> (icmp eq (A & (B|D)), 0)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000559 Value *NewOr = Builder->CreateOr(B, D);
560 Value *NewAnd = Builder->CreateAnd(A, NewOr);
561 // We can't use C as zero because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000562 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000563 // with B and D, having a single bit set.
564 Value *Zero = Constant::getNullValue(A->getType());
565 return Builder->CreateICmp(NewCC, NewAnd, Zero);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000566 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000567 if (Mask & BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000568 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000569 // -> (icmp eq (A & (B|D)), (B|D))
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000570 Value *NewOr = Builder->CreateOr(B, D);
571 Value *NewAnd = Builder->CreateAnd(A, NewOr);
572 return Builder->CreateICmp(NewCC, NewAnd, NewOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000573 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000574 if (Mask & AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000575 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000576 // -> (icmp eq (A & (B&D)), A)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000577 Value *NewAnd1 = Builder->CreateAnd(B, D);
578 Value *NewAnd2 = Builder->CreateAnd(A, NewAnd1);
579 return Builder->CreateICmp(NewCC, NewAnd2, A);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000580 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000581
582 // Remaining cases assume at least that B and D are constant, and depend on
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000583 // their actual values. This isn't strictly necessary, just a "handle the
Tim Northoverc0756c42013-09-04 11:57:13 +0000584 // easy cases for now" decision.
585 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000586 if (!BCst)
587 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000588 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000589 if (!DCst)
590 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000591
Sanjay Patel77bf6222017-04-03 16:53:12 +0000592 if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000593 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
594 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
595 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
596 // Only valid if one of the masks is a superset of the other (check "B&D" is
597 // the same as either B or D).
598 APInt NewMask = BCst->getValue() & DCst->getValue();
599
600 if (NewMask == BCst->getValue())
601 return LHS;
602 else if (NewMask == DCst->getValue())
603 return RHS;
604 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000605
606 if (Mask & AMask_NotAllOnes) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000607 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
608 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
609 // Only valid if one of the masks is a superset of the other (check "B|D" is
610 // the same as either B or D).
611 APInt NewMask = BCst->getValue() | DCst->getValue();
612
613 if (NewMask == BCst->getValue())
614 return LHS;
615 else if (NewMask == DCst->getValue())
616 return RHS;
617 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000618
619 if (Mask & BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000620 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000621 // We already know that B & C == C && D & E == E.
622 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
623 // C and E, which are shared by both the mask B and the mask D, don't
624 // contradict, then we can transform to
625 // -> (icmp eq (A & (B|D)), (C|E))
626 // Currently, we only handle the case of B, C, D, and E being constant.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000627 // We can't simply use C and E because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000628 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000629 // with B and D, having a single bit set.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000630 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000631 if (!CCst)
632 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000633 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000634 if (!ECst)
635 return nullptr;
636 if (PredL != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000637 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000638 if (PredR != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000639 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000640
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000641 // If there is a conflict, we should actually return a false for the
642 // whole construct.
David Majnemer1a3327b2014-11-18 09:31:36 +0000643 if (((BCst->getValue() & DCst->getValue()) &
Craig Topper73ba1c82017-06-07 07:40:37 +0000644 (CCst->getValue() ^ ECst->getValue())).getBoolValue())
David Majnemer6fdb6b82014-11-18 09:31:41 +0000645 return ConstantInt::get(LHS->getType(), !IsAnd);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000646
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000647 Value *NewOr1 = Builder->CreateOr(B, D);
648 Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
649 Value *NewAnd = Builder->CreateAnd(A, NewOr1);
650 return Builder->CreateICmp(NewCC, NewAnd, NewOr2);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000651 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000652
Craig Topperf40110f2014-04-25 05:29:35 +0000653 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000654}
655
Erik Ecksteind1817522014-12-03 10:39:15 +0000656/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
657/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
658/// If \p Inverted is true then the check is for the inverted range, e.g.
659/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
660Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
661 bool Inverted) {
662 // Check the lower range comparison, e.g. x >= 0
663 // InstCombine already ensured that if there is a constant it's on the RHS.
664 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
665 if (!RangeStart)
666 return nullptr;
667
668 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
669 Cmp0->getPredicate());
670
671 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
672 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
673 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
674 return nullptr;
675
676 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
677 Cmp1->getPredicate());
678
679 Value *Input = Cmp0->getOperand(0);
680 Value *RangeEnd;
681 if (Cmp1->getOperand(0) == Input) {
682 // For the upper range compare we have: icmp x, n
683 RangeEnd = Cmp1->getOperand(1);
684 } else if (Cmp1->getOperand(1) == Input) {
685 // For the upper range compare we have: icmp n, x
686 RangeEnd = Cmp1->getOperand(0);
687 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
688 } else {
689 return nullptr;
690 }
691
692 // Check the upper range comparison, e.g. x < n
693 ICmpInst::Predicate NewPred;
694 switch (Pred1) {
695 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
696 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
697 default: return nullptr;
698 }
699
700 // This simplification is only valid if the upper range is not negative.
Craig Topper1a36b7d2017-05-15 06:39:41 +0000701 KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
702 if (!Known.isNonNegative())
Erik Ecksteind1817522014-12-03 10:39:15 +0000703 return nullptr;
704
705 if (Inverted)
706 NewPred = ICmpInst::getInversePredicate(NewPred);
707
708 return Builder->CreateICmp(NewPred, Input, RangeEnd);
709}
710
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000711static Value *
712foldAndOrOfEqualityCmpsWithConstants(ICmpInst *LHS, ICmpInst *RHS,
713 bool JoinedByAnd,
714 InstCombiner::BuilderTy *Builder) {
Sanjay Patelef9f5862017-04-15 17:55:06 +0000715 Value *X = LHS->getOperand(0);
716 if (X != RHS->getOperand(0))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000717 return nullptr;
718
Sanjay Patelef9f5862017-04-15 17:55:06 +0000719 const APInt *C1, *C2;
720 if (!match(LHS->getOperand(1), m_APInt(C1)) ||
721 !match(RHS->getOperand(1), m_APInt(C2)))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000722 return nullptr;
723
724 // We only handle (X != C1 && X != C2) and (X == C1 || X == C2).
725 ICmpInst::Predicate Pred = LHS->getPredicate();
726 if (Pred != RHS->getPredicate())
727 return nullptr;
728 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
729 return nullptr;
730 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
731 return nullptr;
732
733 // The larger unsigned constant goes on the right.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000734 if (C1->ugt(*C2))
735 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000736
Sanjay Patelef9f5862017-04-15 17:55:06 +0000737 APInt Xor = *C1 ^ *C2;
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000738 if (Xor.isPowerOf2()) {
739 // If LHSC and RHSC differ by only one bit, then set that bit in X and
740 // compare against the larger constant:
741 // (X == C1 || X == C2) --> (X | (C1 ^ C2)) == C2
742 // (X != C1 && X != C2) --> (X | (C1 ^ C2)) != C2
743 // We choose an 'or' with a Pow2 constant rather than the inverse mask with
744 // 'and' because that may lead to smaller codegen from a smaller constant.
745 Value *Or = Builder->CreateOr(X, ConstantInt::get(X->getType(), Xor));
Sanjay Patelef9f5862017-04-15 17:55:06 +0000746 return Builder->CreateICmp(Pred, Or, ConstantInt::get(X->getType(), *C2));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000747 }
748
749 // Special case: get the ordering right when the values wrap around zero.
750 // Ie, we assumed the constants were unsigned when swapping earlier.
Craig Topper73ba1c82017-06-07 07:40:37 +0000751 if (C1->isNullValue() && C2->isAllOnesValue())
Sanjay Patelef9f5862017-04-15 17:55:06 +0000752 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000753
Sanjay Patelef9f5862017-04-15 17:55:06 +0000754 if (*C1 == *C2 - 1) {
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000755 // (X == 13 || X == 14) --> X - 13 <=u 1
756 // (X != 13 && X != 14) --> X - 13 >u 1
757 // An 'add' is the canonical IR form, so favor that over a 'sub'.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000758 Value *Add = Builder->CreateAdd(X, ConstantInt::get(X->getType(), -(*C1)));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000759 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
760 return Builder->CreateICmp(NewPred, Add, ConstantInt::get(X->getType(), 1));
761 }
762
763 return nullptr;
764}
765
Craig Topperda6ea0d2017-06-16 05:10:37 +0000766// Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
767// Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
768Value *InstCombiner::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS,
769 bool JoinedByAnd,
770 Instruction &CxtI) {
771 ICmpInst::Predicate Pred = LHS->getPredicate();
772 if (Pred != RHS->getPredicate())
773 return nullptr;
774 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
775 return nullptr;
776 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
777 return nullptr;
778
779 // TODO support vector splats
780 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
781 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
782 if (!LHSC || !RHSC || !LHSC->isZero() || !RHSC->isZero())
783 return nullptr;
784
785 Value *A, *B, *C, *D;
786 if (match(LHS->getOperand(0), m_And(m_Value(A), m_Value(B))) &&
787 match(RHS->getOperand(0), m_And(m_Value(C), m_Value(D)))) {
788 if (A == D || B == D)
789 std::swap(C, D);
790 if (B == C)
791 std::swap(A, B);
792
793 if (A == C &&
794 isKnownToBeAPowerOfTwo(B, false, 0, &CxtI) &&
795 isKnownToBeAPowerOfTwo(D, false, 0, &CxtI)) {
796 Value *Mask = Builder->CreateOr(B, D);
797 Value *Masked = Builder->CreateAnd(A, Mask);
798 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
799 return Builder->CreateICmp(NewPred, Masked, Mask);
800 }
801 }
802
803 return nullptr;
804}
805
Sanjay Patel18549272015-09-08 18:24:36 +0000806/// Fold (icmp)&(icmp) if possible.
Craig Topperda6ea0d2017-06-16 05:10:37 +0000807Value *InstCombiner::foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS,
808 Instruction &CxtI) {
809 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
810 // if K1 and K2 are a one-bit mask.
811 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, true, CxtI))
812 return V;
813
Sanjay Patel519a87a2017-04-05 17:38:34 +0000814 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000815
816 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000817 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000818 if (LHS->getOperand(0) == RHS->getOperand(1) &&
819 LHS->getOperand(1) == RHS->getOperand(0))
820 LHS->swapOperands();
821 if (LHS->getOperand(0) == RHS->getOperand(0) &&
822 LHS->getOperand(1) == RHS->getOperand(1)) {
823 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
824 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
825 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000826 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000827 }
828 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000829
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000830 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000831 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000832 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000833
Erik Ecksteind1817522014-12-03 10:39:15 +0000834 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
835 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
836 return V;
837
838 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
839 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
840 return V;
841
Sanjay Patelef9f5862017-04-15 17:55:06 +0000842 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, true, Builder))
843 return V;
844
Chris Lattner0a8191e2010-01-05 07:50:36 +0000845 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Sanjay Patele4159d22017-04-10 19:38:36 +0000846 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000847 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
848 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
849 if (!LHSC || !RHSC)
850 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000851
Sanjay Patel519a87a2017-04-05 17:38:34 +0000852 if (LHSC == RHSC && PredL == PredR) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000853 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000854 // where C is a power of 2 or
Chris Lattner0a8191e2010-01-05 07:50:36 +0000855 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000856 if ((PredL == ICmpInst::ICMP_ULT && LHSC->getValue().isPowerOf2()) ||
857 (PredL == ICmpInst::ICMP_EQ && LHSC->isZero())) {
Sanjay Patele4159d22017-04-10 19:38:36 +0000858 Value *NewOr = Builder->CreateOr(LHS0, RHS0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000859 return Builder->CreateICmp(PredL, NewOr, LHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000860 }
861 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000862
Benjamin Kramer101720f2011-04-28 20:09:57 +0000863 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000864 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000865 // iff the lower bits of C2 and CA are zero.
Sanjay Patel519a87a2017-04-05 17:38:34 +0000866 if (PredL == ICmpInst::ICMP_EQ && PredL == PredR && LHS->hasOneUse() &&
867 RHS->hasOneUse()) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000868 Value *V;
Sanjay Patel519a87a2017-04-05 17:38:34 +0000869 ConstantInt *AndC, *SmallC = nullptr, *BigC = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000870
871 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000872 // (and x, CA) == C2 & (trunc x) == C1
Sanjay Patele4159d22017-04-10 19:38:36 +0000873 if (match(RHS0, m_Trunc(m_Value(V))) &&
874 match(LHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000875 SmallC = RHSC;
876 BigC = LHSC;
Sanjay Patele4159d22017-04-10 19:38:36 +0000877 } else if (match(LHS0, m_Trunc(m_Value(V))) &&
878 match(RHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000879 SmallC = LHSC;
880 BigC = RHSC;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000881 }
882
Sanjay Patel519a87a2017-04-05 17:38:34 +0000883 if (SmallC && BigC) {
884 unsigned BigBitSize = BigC->getType()->getBitWidth();
885 unsigned SmallBitSize = SmallC->getType()->getBitWidth();
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000886
887 // Check that the low bits are zero.
888 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Craig Topper73ba1c82017-06-07 07:40:37 +0000889 if ((Low & AndC->getValue()).isNullValue() &&
890 (Low & BigC->getValue()).isNullValue()) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000891 Value *NewAnd = Builder->CreateAnd(V, Low | AndC->getValue());
892 APInt N = SmallC->getValue().zext(BigBitSize) | BigC->getValue();
893 Value *NewVal = ConstantInt::get(AndC->getType()->getContext(), N);
894 return Builder->CreateICmp(PredL, NewAnd, NewVal);
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000895 }
896 }
897 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000898
Chris Lattner0a8191e2010-01-05 07:50:36 +0000899 // From here on, we only handle:
900 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +0000901 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000902 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000903
Sanjay Patel519a87a2017-04-05 17:38:34 +0000904 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
905 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
906 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
907 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
908 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000909 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000910
Chris Lattner0a8191e2010-01-05 07:50:36 +0000911 // We can't fold (ugt x, C) & (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +0000912 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +0000913 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000914
Chris Lattner0a8191e2010-01-05 07:50:36 +0000915 // Ensure that the larger constant is on the RHS.
916 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +0000917 if (CmpInst::isSigned(PredL) ||
918 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +0000919 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +0000920 else
921 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000922
Chris Lattner0a8191e2010-01-05 07:50:36 +0000923 if (ShouldSwap) {
924 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000925 std::swap(LHSC, RHSC);
926 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000927 }
928
Dan Gohman4a618822010-02-10 16:03:48 +0000929 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000930 // comparing a value against two constants and and'ing the result
931 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +0000932 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
933 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +0000934 // are not equal and that the larger constant is on the RHS
Sanjay Patel519a87a2017-04-05 17:38:34 +0000935 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000936
Sanjay Patel519a87a2017-04-05 17:38:34 +0000937 switch (PredL) {
938 default:
939 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000940 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000941 switch (PredR) {
942 default:
943 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000944 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000945 if (LHSC == SubOne(RHSC)) // (X != 13 & X u< 14) -> X < 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000946 return Builder->CreateICmpULT(LHS0, LHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000947 if (LHSC->isNullValue()) // (X != 0 & X u< 14) -> X-1 u< 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000948 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
Sanjay Patel85d79742016-08-31 19:49:56 +0000949 false, true);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000950 break; // (X != 13 & X u< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000951 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000952 if (LHSC == SubOne(RHSC)) // (X != 13 & X s< 14) -> X < 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000953 return Builder->CreateICmpSLT(LHS0, LHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000954 break; // (X != 13 & X s< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000955 case ICmpInst::ICMP_NE:
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000956 // Potential folds for this case should already be handled.
957 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000958 }
959 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000960 case ICmpInst::ICMP_UGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000961 switch (PredR) {
962 default:
963 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000964 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000965 if (RHSC == AddOne(LHSC)) // (X u> 13 & X != 14) -> X u> 14
Sanjay Patele4159d22017-04-10 19:38:36 +0000966 return Builder->CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000967 break; // (X u> 13 & X != 15) -> no change
968 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000969 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
970 false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000971 }
972 break;
973 case ICmpInst::ICMP_SGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000974 switch (PredR) {
975 default:
976 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000977 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000978 if (RHSC == AddOne(LHSC)) // (X s> 13 & X != 14) -> X s> 14
Sanjay Patele4159d22017-04-10 19:38:36 +0000979 return Builder->CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000980 break; // (X s> 13 & X != 15) -> no change
981 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000982 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(), true,
Sanjay Patel519a87a2017-04-05 17:38:34 +0000983 true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000984 }
985 break;
986 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000987
Craig Topperf40110f2014-04-25 05:29:35 +0000988 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000989}
990
Sanjay Patel18549272015-09-08 18:24:36 +0000991/// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
992/// a Value which should already be inserted into the function.
Sanjay Patel5e456b92017-05-18 20:53:16 +0000993Value *InstCombiner::foldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +0000994 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
995 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
996 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
997
998 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
999 // Swap RHS operands to match LHS.
1000 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1001 std::swap(Op1LHS, Op1RHS);
1002 }
1003
1004 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1005 // Suppose the relation between x and y is R, where R is one of
1006 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
1007 // testing the desired relations.
1008 //
1009 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1010 // bool(R & CC0) && bool(R & CC1)
1011 // = bool((R & CC0) & (R & CC1))
1012 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
1013 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1014 return getFCmpValue(getFCmpCode(Op0CC) & getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1015 Builder);
1016
Chris Lattner0a8191e2010-01-05 07:50:36 +00001017 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1018 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +00001019 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001020 return nullptr;
Benjamin Kramere89c7052013-04-12 21:56:23 +00001021
Chris Lattner0a8191e2010-01-05 07:50:36 +00001022 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1023 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1024 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1025 // If either of the constants are nans, then the whole thing returns
1026 // false.
1027 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001028 return Builder->getFalse();
Chris Lattner067459c2010-03-05 08:46:26 +00001029 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001030 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001031
Chris Lattner0a8191e2010-01-05 07:50:36 +00001032 // Handle vector zeros. This occurs because the canonical form of
1033 // "fcmp ord x,x" is "fcmp ord x, 0".
1034 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1035 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001036 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001037 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001038 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001039
Craig Topperf40110f2014-04-25 05:29:35 +00001040 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001041}
1042
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001043/// Match De Morgan's Laws:
1044/// (~A & ~B) == (~(A | B))
1045/// (~A | ~B) == (~(A & B))
1046static Instruction *matchDeMorgansLaws(BinaryOperator &I,
Sanjay Patel7caaa792017-05-09 20:05:05 +00001047 InstCombiner::BuilderTy &Builder) {
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001048 auto Opcode = I.getOpcode();
1049 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1050 "Trying to match De Morgan's Laws with something other than and/or");
1051
Sanjay Patel7caaa792017-05-09 20:05:05 +00001052 // Flip the logic operation.
1053 Opcode = (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
1054
1055 Value *A, *B;
1056 if (match(I.getOperand(0), m_OneUse(m_Not(m_Value(A)))) &&
1057 match(I.getOperand(1), m_OneUse(m_Not(m_Value(B)))) &&
1058 !IsFreeToInvert(A, A->hasOneUse()) &&
1059 !IsFreeToInvert(B, B->hasOneUse())) {
1060 Value *AndOr = Builder.CreateBinOp(Opcode, A, B, I.getName() + ".demorgan");
1061 return BinaryOperator::CreateNot(AndOr);
1062 }
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001063
1064 return nullptr;
1065}
1066
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001067bool InstCombiner::shouldOptimizeCast(CastInst *CI) {
1068 Value *CastSrc = CI->getOperand(0);
1069
1070 // Noop casts and casts of constants should be eliminated trivially.
1071 if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
1072 return false;
1073
1074 // If this cast is paired with another cast that can be eliminated, we prefer
1075 // to have it eliminated.
1076 if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
1077 if (isEliminableCastPair(PrecedingCI, CI))
1078 return false;
1079
1080 // If this is a vector sext from a compare, then we don't want to break the
1081 // idiom where each element of the extended vector is either zero or all ones.
1082 if (CI->getOpcode() == Instruction::SExt &&
1083 isa<CmpInst>(CastSrc) && CI->getDestTy()->isVectorTy())
1084 return false;
1085
1086 return true;
1087}
1088
Sanjay Patel60312bc42016-09-12 00:16:23 +00001089/// Fold {and,or,xor} (cast X), C.
1090static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
1091 InstCombiner::BuilderTy *Builder) {
1092 Constant *C;
1093 if (!match(Logic.getOperand(1), m_Constant(C)))
1094 return nullptr;
1095
1096 auto LogicOpc = Logic.getOpcode();
1097 Type *DestTy = Logic.getType();
1098 Type *SrcTy = Cast->getSrcTy();
1099
Sanjay Pateld1e81192017-06-22 15:46:54 +00001100 // Move the logic operation ahead of a zext if the constant is unchanged in
1101 // the smaller source type. Performing the logic in a smaller type may provide
1102 // more information to later folds, and the smaller logic instruction may be
1103 // cheaper (particularly in the case of vectors).
Sanjay Patel60312bc42016-09-12 00:16:23 +00001104 Value *X;
Sanjay Patel60312bc42016-09-12 00:16:23 +00001105 if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1106 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1107 Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1108 if (ZextTruncC == C) {
1109 // LogicOpc (zext X), C --> zext (LogicOpc X, C)
1110 Value *NewOp = Builder->CreateBinOp(LogicOpc, X, TruncC);
1111 return new ZExtInst(NewOp, DestTy);
1112 }
1113 }
1114
1115 return nullptr;
1116}
1117
1118/// Fold {and,or,xor} (cast X), Y.
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001119Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001120 auto LogicOpc = I.getOpcode();
Sanjay Patel1e6ca442016-11-22 22:54:36 +00001121 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001122
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001123 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001124 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
Sanjay Patel9bba7502016-03-03 19:19:04 +00001125 if (!Cast0)
Sanjay Patel7d0d8102016-02-23 16:59:21 +00001126 return nullptr;
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001127
Sanjay Patel9bba7502016-03-03 19:19:04 +00001128 // This must be a cast from an integer or integer vector source type to allow
1129 // transformation of the logic operation to the source type.
1130 Type *DestTy = I.getType();
Sanjay Patel713f25e2016-02-23 17:41:34 +00001131 Type *SrcTy = Cast0->getSrcTy();
Sanjay Patel9bba7502016-03-03 19:19:04 +00001132 if (!SrcTy->isIntOrIntVectorTy())
1133 return nullptr;
1134
Sanjay Patel60312bc42016-09-12 00:16:23 +00001135 if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1136 return Ret;
Sanjay Patel0753c062016-07-21 00:24:18 +00001137
Sanjay Patel9bba7502016-03-03 19:19:04 +00001138 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1139 if (!Cast1)
1140 return nullptr;
1141
1142 // Both operands of the logic operation are casts. The casts must be of the
1143 // same type for reduction.
1144 auto CastOpcode = Cast0->getOpcode();
1145 if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
Sanjay Patel713f25e2016-02-23 17:41:34 +00001146 return nullptr;
1147
1148 Value *Cast0Src = Cast0->getOperand(0);
1149 Value *Cast1Src = Cast1->getOperand(0);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001150
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001151 // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
Tobias Grosser8757e382016-08-03 19:30:35 +00001152 if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001153 Value *NewOp = Builder->CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
1154 I.getName());
Sanjay Patel713f25e2016-02-23 17:41:34 +00001155 return CastInst::Create(CastOpcode, NewOp, DestTy);
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001156 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001157
Sanjay Pateldbbaca02016-02-24 17:00:34 +00001158 // For now, only 'and'/'or' have optimizations after this.
1159 if (LogicOpc == Instruction::Xor)
1160 return nullptr;
1161
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001162 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001163 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001164 ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1165 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1166 if (ICmp0 && ICmp1) {
Craig Topperda6ea0d2017-06-16 05:10:37 +00001167 Value *Res = LogicOpc == Instruction::And ? foldAndOfICmps(ICmp0, ICmp1, I)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001168 : foldOrOfICmps(ICmp0, ICmp1, I);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001169 if (Res)
1170 return CastInst::Create(CastOpcode, Res, DestTy);
1171 return nullptr;
1172 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001173
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001174 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001175 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001176 FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1177 FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1178 if (FCmp0 && FCmp1) {
Sanjay Patel5e456b92017-05-18 20:53:16 +00001179 Value *Res = LogicOpc == Instruction::And ? foldAndOfFCmps(FCmp0, FCmp1)
1180 : foldOrOfFCmps(FCmp0, FCmp1);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001181 if (Res)
1182 return CastInst::Create(CastOpcode, Res, DestTy);
1183 return nullptr;
1184 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001185
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001186 return nullptr;
1187}
1188
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001189static Instruction *foldBoolSextMaskToSelect(BinaryOperator &I) {
1190 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1191
1192 // Canonicalize SExt or Not to the LHS
1193 if (match(Op1, m_SExt(m_Value())) || match(Op1, m_Not(m_Value()))) {
1194 std::swap(Op0, Op1);
1195 }
1196
1197 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1198 Value *X = nullptr;
1199 if (match(Op0, m_SExt(m_Value(X))) &&
1200 X->getType()->getScalarType()->isIntegerTy(1)) {
1201 Value *Zero = Constant::getNullValue(Op1->getType());
1202 return SelectInst::Create(X, Op1, Zero);
1203 }
1204
1205 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1206 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1207 X->getType()->getScalarType()->isIntegerTy(1)) {
1208 Value *Zero = Constant::getNullValue(Op0->getType());
1209 return SelectInst::Create(X, Zero, Op1);
1210 }
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001211
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001212 return nullptr;
1213}
1214
Sanjay Patele0c26e02017-04-23 22:00:02 +00001215static Instruction *foldAndToXor(BinaryOperator &I,
1216 InstCombiner::BuilderTy &Builder) {
1217 assert(I.getOpcode() == Instruction::And);
1218 Value *Op0 = I.getOperand(0);
1219 Value *Op1 = I.getOperand(1);
1220 Value *A, *B;
1221
1222 // Operand complexity canonicalization guarantees that the 'or' is Op0.
1223 // (A | B) & ~(A & B) --> A ^ B
1224 // (A | B) & ~(B & A) --> A ^ B
1225 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1226 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B)))))
1227 return BinaryOperator::CreateXor(A, B);
1228
1229 // (A | ~B) & (~A | B) --> ~(A ^ B)
1230 // (A | ~B) & (B | ~A) --> ~(A ^ B)
1231 // (~B | A) & (~A | B) --> ~(A ^ B)
1232 // (~B | A) & (B | ~A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001233 if (Op0->hasOneUse() || Op1->hasOneUse())
1234 if (match(Op0, m_c_Or(m_Value(A), m_Not(m_Value(B)))) &&
1235 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B))))
1236 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001237
1238 return nullptr;
1239}
1240
1241static Instruction *foldOrToXor(BinaryOperator &I,
1242 InstCombiner::BuilderTy &Builder) {
1243 assert(I.getOpcode() == Instruction::Or);
1244 Value *Op0 = I.getOperand(0);
1245 Value *Op1 = I.getOperand(1);
1246 Value *A, *B;
1247
1248 // Operand complexity canonicalization guarantees that the 'and' is Op0.
1249 // (A & B) | ~(A | B) --> ~(A ^ B)
1250 // (A & B) | ~(B | A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001251 if (Op0->hasOneUse() || Op1->hasOneUse())
1252 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1253 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1254 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001255
1256 // (A & ~B) | (~A & B) --> A ^ B
1257 // (A & ~B) | (B & ~A) --> A ^ B
1258 // (~B & A) | (~A & B) --> A ^ B
1259 // (~B & A) | (B & ~A) --> A ^ B
1260 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
1261 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
1262 return BinaryOperator::CreateXor(A, B);
1263
1264 return nullptr;
1265}
1266
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001267// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1268// here. We should standardize that construct where it is needed or choose some
1269// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001270Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001271 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001272 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1273
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001274 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001275 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001276
Craig Toppera4205622017-06-09 03:21:29 +00001277 if (Value *V = SimplifyAndInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001278 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001279
Craig Topper9d4171a2012-12-20 07:09:41 +00001280 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001281 // purpose is to compute bits we don't care about.
1282 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001283 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001284
Sanjay Patele0c26e02017-04-23 22:00:02 +00001285 // Do this before using distributive laws to catch simple and/or/not patterns.
1286 if (Instruction *Xor = foldAndToXor(I, *Builder))
1287 return Xor;
1288
1289 // (A|B)&(A|C) -> A|(B&C) etc
1290 if (Value *V = SimplifyUsingDistributiveLaws(I))
1291 return replaceInstUsesWith(I, V);
1292
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001293 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001294 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001295
Chris Lattner0a8191e2010-01-05 07:50:36 +00001296 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1297 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001298
1299 // Optimize a variety of ((val OP C1) & C2) combinations...
1300 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1301 Value *Op0LHS = Op0I->getOperand(0);
1302 Value *Op0RHS = Op0I->getOperand(1);
1303 switch (Op0I->getOpcode()) {
1304 default: break;
1305 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001306 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001307 // If the mask is only needed on one incoming arm, push it up.
1308 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001309
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001310 APInt NotAndRHS(~AndRHSMask);
Hal Finkel60db0582014-09-07 18:57:58 +00001311 if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001312 // Not masking anything out for the LHS, move to RHS.
1313 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1314 Op0RHS->getName()+".masked");
1315 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1316 }
1317 if (!isa<Constant>(Op0RHS) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001318 MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001319 // Not masking anything out for the RHS, move to LHS.
1320 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1321 Op0LHS->getName()+".masked");
1322 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1323 }
1324
1325 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001326 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001327 case Instruction::Sub:
Balaram Makamccf59732015-08-20 15:35:00 +00001328 // -x & 1 -> x & 1
Craig Topper73ba1c82017-06-07 07:40:37 +00001329 if (AndRHSMask.isOneValue() && match(Op0LHS, m_Zero()))
Balaram Makamccf59732015-08-20 15:35:00 +00001330 return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
1331
Chris Lattner0a8191e2010-01-05 07:50:36 +00001332 break;
1333
1334 case Instruction::Shl:
1335 case Instruction::LShr:
1336 // (1 << x) & 1 --> zext(x == 0)
1337 // (1 >> x) & 1 --> zext(x == 0)
Craig Topper73ba1c82017-06-07 07:40:37 +00001338 if (AndRHSMask.isOneValue() && Op0LHS == AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001339 Value *NewICmp =
1340 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1341 return new ZExtInst(NewICmp, I.getType());
1342 }
1343 break;
1344 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001345
David Majnemerde55c602017-01-17 18:08:06 +00001346 // ((C1 OP zext(X)) & C2) -> zext((C1-X) & C2) if C2 fits in the bitwidth
1347 // of X and OP behaves well when given trunc(C1) and X.
1348 switch (Op0I->getOpcode()) {
1349 default:
1350 break;
1351 case Instruction::Xor:
1352 case Instruction::Or:
1353 case Instruction::Mul:
1354 case Instruction::Add:
1355 case Instruction::Sub:
1356 Value *X;
1357 ConstantInt *C1;
Craig Topperb5194ee2017-04-12 05:49:28 +00001358 if (match(Op0I, m_c_BinOp(m_ZExt(m_Value(X)), m_ConstantInt(C1)))) {
David Majnemerde55c602017-01-17 18:08:06 +00001359 if (AndRHSMask.isIntN(X->getType()->getScalarSizeInBits())) {
1360 auto *TruncC1 = ConstantExpr::getTrunc(C1, X->getType());
1361 Value *BinOp;
1362 if (isa<ZExtInst>(Op0LHS))
1363 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), X, TruncC1);
1364 else
1365 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), TruncC1, X);
1366 auto *TruncC2 = ConstantExpr::getTrunc(AndRHS, X->getType());
1367 auto *And = Builder->CreateAnd(BinOp, TruncC2);
1368 return new ZExtInst(And, I.getType());
1369 }
1370 }
1371 }
1372
Chris Lattner0a8191e2010-01-05 07:50:36 +00001373 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1374 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1375 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001376 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001377
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001378 // If this is an integer truncation, and if the source is an 'and' with
1379 // immediate, transform it. This frequently occurs for bitfield accesses.
1380 {
Craig Topperf40110f2014-04-25 05:29:35 +00001381 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001382 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1383 // Change: and (trunc (and X, YC) to T), C2
1384 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001385 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001386 // other simplifications.
1387 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1388 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1389 C3 = ConstantExpr::getAnd(C3, AndRHS);
1390 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001391 }
1392 }
Craig Topper86173602017-04-04 20:26:25 +00001393 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001394
Craig Topper86173602017-04-04 20:26:25 +00001395 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001396 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1397 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001398
Sanjay Patel7caaa792017-05-09 20:05:05 +00001399 if (Instruction *DeMorgan = matchDeMorgansLaws(I, *Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001400 return DeMorgan;
Craig Topper9d4171a2012-12-20 07:09:41 +00001401
Chris Lattner0a8191e2010-01-05 07:50:36 +00001402 {
Sanjay Patele0c26e02017-04-23 22:00:02 +00001403 Value *A = nullptr, *B = nullptr, *C = nullptr;
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001404 // A&(A^B) => A & ~B
1405 {
1406 Value *tmpOp0 = Op0;
1407 Value *tmpOp1 = Op1;
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001408 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001409 if (A == Op1 || B == Op1 ) {
1410 tmpOp1 = Op0;
1411 tmpOp0 = Op1;
1412 // Simplify below
1413 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001414 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001415
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001416 if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001417 if (B == tmpOp0) {
1418 std::swap(A, B);
1419 }
Sanjay Pateld09b44a2016-01-18 17:50:23 +00001420 // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001421 // A is originally -1 (or a vector of -1 and undefs), then we enter
1422 // an endless loop. By checking that A is non-constant we ensure that
1423 // we will never get to the loop.
1424 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001425 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001426 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001427 }
1428
1429 // (A&((~A)|B)) -> A&B
Craig Topperc4b48a32017-04-25 06:02:11 +00001430 if (match(Op0, m_c_Or(m_Not(m_Specific(Op1)), m_Value(A))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001431 return BinaryOperator::CreateAnd(A, Op1);
Craig Topperc4b48a32017-04-25 06:02:11 +00001432 if (match(Op1, m_c_Or(m_Not(m_Specific(Op0)), m_Value(A))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001433 return BinaryOperator::CreateAnd(A, Op0);
David Majnemer42af3602014-07-30 21:26:37 +00001434
1435 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1436 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1437 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001438 if (Op1->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
David Majnemer42af3602014-07-30 21:26:37 +00001439 return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1440
1441 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1442 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1443 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001444 if (Op0->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
David Majnemer42af3602014-07-30 21:26:37 +00001445 return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001446
1447 // (A | B) & ((~A) ^ B) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001448 // (A | B) & (B ^ (~A)) -> (A & B)
1449 // (B | A) & ((~A) ^ B) -> (A & B)
1450 // (B | A) & (B ^ (~A)) -> (A & B)
1451 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1452 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001453 return BinaryOperator::CreateAnd(A, B);
1454
1455 // ((~A) ^ B) & (A | B) -> (A & B)
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001456 // ((~A) ^ B) & (B | A) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001457 // (B ^ (~A)) & (A | B) -> (A & B)
1458 // (B ^ (~A)) & (B | A) -> (A & B)
1459 if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001460 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001461 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001462 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001463
David Majnemer5e96f1b2014-08-30 06:18:20 +00001464 {
1465 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1466 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1467 if (LHS && RHS)
Craig Topperda6ea0d2017-06-16 05:10:37 +00001468 if (Value *Res = foldAndOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001469 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001470
David Majnemer5e96f1b2014-08-30 06:18:20 +00001471 // TODO: Make this recursive; it's a little tricky because an arbitrary
1472 // number of 'and' instructions might have to be created.
1473 Value *X, *Y;
1474 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1475 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001476 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001477 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001478 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001479 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001480 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001481 }
1482 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1483 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001484 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001485 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001486 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001487 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001488 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001489 }
1490 }
1491
Chris Lattner4e8137d2010-02-11 06:26:33 +00001492 // If and'ing two fcmp, try combine them into one.
1493 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1494 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel5e456b92017-05-18 20:53:16 +00001495 if (Value *Res = foldAndOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001496 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001497
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001498 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1499 return CastedAnd;
Craig Topper9d4171a2012-12-20 07:09:41 +00001500
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001501 if (Instruction *Select = foldBoolSextMaskToSelect(I))
1502 return Select;
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001503
Craig Topperf40110f2014-04-25 05:29:35 +00001504 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001505}
1506
Chad Rosiera00df492016-05-25 16:22:14 +00001507/// Given an OR instruction, check to see if this is a bswap idiom. If so,
1508/// insert the new intrinsic and return it.
1509Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chad Rosiere5819e22016-05-26 14:58:51 +00001510 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1511
1512 // Look through zero extends.
1513 if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1514 Op0 = Ext->getOperand(0);
1515
1516 if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1517 Op1 = Ext->getOperand(0);
1518
1519 // (A | B) | C and A | (B | C) -> bswap if possible.
1520 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1521 match(Op1, m_Or(m_Value(), m_Value()));
1522
1523 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1524 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1525 match(Op1, m_LogicalShift(m_Value(), m_Value()));
1526
1527 // (A & B) | (C & D) -> bswap if possible.
1528 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1529 match(Op1, m_And(m_Value(), m_Value()));
1530
1531 if (!OrOfOrs && !OrOfShifts && !OrOfAnds)
1532 return nullptr;
1533
James Molloyf01488e2016-01-15 09:20:19 +00001534 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00001535 if (!recognizeBSwapOrBitReverseIdiom(&I, true, false, Insts))
Craig Topperf40110f2014-04-25 05:29:35 +00001536 return nullptr;
James Molloyf01488e2016-01-15 09:20:19 +00001537 Instruction *LastInst = Insts.pop_back_val();
1538 LastInst->removeFromParent();
Craig Topper9d4171a2012-12-20 07:09:41 +00001539
James Molloyf01488e2016-01-15 09:20:19 +00001540 for (auto *Inst : Insts)
1541 Worklist.Add(Inst);
1542 return LastInst;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001543}
1544
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001545/// If all elements of two constant vectors are 0/-1 and inverses, return true.
1546static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
1547 unsigned NumElts = C1->getType()->getVectorNumElements();
1548 for (unsigned i = 0; i != NumElts; ++i) {
1549 Constant *EltC1 = C1->getAggregateElement(i);
1550 Constant *EltC2 = C2->getAggregateElement(i);
1551 if (!EltC1 || !EltC2)
1552 return false;
1553
1554 // One element must be all ones, and the other must be all zeros.
1555 // FIXME: Allow undef elements.
1556 if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
1557 (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
1558 return false;
1559 }
1560 return true;
1561}
1562
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001563/// We have an expression of the form (A & C) | (B & D). If A is a scalar or
1564/// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
1565/// B, it can be used as the condition operand of a select instruction.
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001566static Value *getSelectCondition(Value *A, Value *B,
1567 InstCombiner::BuilderTy &Builder) {
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001568 // If these are scalars or vectors of i1, A can be used directly.
1569 Type *Ty = A->getType();
1570 if (match(A, m_Not(m_Specific(B))) && Ty->getScalarType()->isIntegerTy(1))
1571 return A;
1572
1573 // If A and B are sign-extended, look through the sexts to find the booleans.
1574 Value *Cond;
Sanjay Pateld1e81192017-06-22 15:46:54 +00001575 Value *NotB;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001576 if (match(A, m_SExt(m_Value(Cond))) &&
1577 Cond->getType()->getScalarType()->isIntegerTy(1) &&
Sanjay Pateld1e81192017-06-22 15:46:54 +00001578 match(B, m_OneUse(m_Not(m_Value(NotB))))) {
1579 NotB = peekThroughBitcast(NotB, true);
1580 if (match(NotB, m_SExt(m_Specific(Cond))))
1581 return Cond;
1582 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001583
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001584 // All scalar (and most vector) possibilities should be handled now.
1585 // Try more matches that only apply to non-splat constant vectors.
1586 if (!Ty->isVectorTy())
1587 return nullptr;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001588
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001589 // If both operands are constants, see if the constants are inverse bitmasks.
1590 Constant *AC, *BC;
1591 if (match(A, m_Constant(AC)) && match(B, m_Constant(BC)) &&
1592 areInverseVectorBitmasks(AC, BC))
1593 return ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1594
1595 // If both operands are xor'd with constants using the same sexted boolean
1596 // operand, see if the constants are inverse bitmasks.
1597 if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AC)))) &&
1598 match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BC)))) &&
1599 Cond->getType()->getScalarType()->isIntegerTy(1) &&
1600 areInverseVectorBitmasks(AC, BC)) {
1601 AC = ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1602 return Builder.CreateXor(Cond, AC);
1603 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001604 return nullptr;
1605}
1606
1607/// We have an expression of the form (A & C) | (B & D). Try to simplify this
1608/// to "A' ? C : D", where A' is a boolean or vector of booleans.
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001609static Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D,
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001610 InstCombiner::BuilderTy &Builder) {
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001611 // The potential condition of the select may be bitcasted. In that case, look
1612 // through its bitcast and the corresponding bitcast of the 'not' condition.
1613 Type *OrigType = A->getType();
Sanjay Patele800df8e2017-06-22 15:28:01 +00001614 A = peekThroughBitcast(A, true);
1615 B = peekThroughBitcast(B, true);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001616
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001617 if (Value *Cond = getSelectCondition(A, B, Builder)) {
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001618 // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001619 // The bitcasts will either all exist or all not exist. The builder will
1620 // not create unnecessary casts if the types already match.
1621 Value *BitcastC = Builder.CreateBitCast(C, A->getType());
1622 Value *BitcastD = Builder.CreateBitCast(D, A->getType());
1623 Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
1624 return Builder.CreateBitCast(Select, OrigType);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001625 }
Sanjay Patel5c0bc022016-06-02 18:03:05 +00001626
Craig Topperf40110f2014-04-25 05:29:35 +00001627 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001628}
1629
Sanjay Patel18549272015-09-08 18:24:36 +00001630/// Fold (icmp)|(icmp) if possible.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001631Value *InstCombiner::foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001632 Instruction &CxtI) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001633 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1634 // if K1 and K2 are a one-bit mask.
Craig Topperda6ea0d2017-06-16 05:10:37 +00001635 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, false, CxtI))
1636 return V;
1637
1638 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1639
Sanjay Patel519a87a2017-04-05 17:38:34 +00001640 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
1641 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001642
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001643 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1644 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1645 // The original condition actually refers to the following two ranges:
1646 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1647 // We can fold these two ranges if:
1648 // 1) C1 and C2 is unsigned greater than C3.
1649 // 2) The two ranges are separated.
1650 // 3) C1 ^ C2 is one-bit mask.
1651 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1652 // This implies all values in the two ranges differ by exactly one bit.
1653
Sanjay Patel519a87a2017-04-05 17:38:34 +00001654 if ((PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) &&
1655 PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() &&
1656 LHSC->getType() == RHSC->getType() &&
1657 LHSC->getValue() == (RHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001658
1659 Value *LAdd = LHS->getOperand(0);
1660 Value *RAdd = RHS->getOperand(0);
1661
1662 Value *LAddOpnd, *RAddOpnd;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001663 ConstantInt *LAddC, *RAddC;
1664 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddC))) &&
1665 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddC))) &&
1666 LAddC->getValue().ugt(LHSC->getValue()) &&
1667 RAddC->getValue().ugt(LHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001668
Sanjay Patel519a87a2017-04-05 17:38:34 +00001669 APInt DiffC = LAddC->getValue() ^ RAddC->getValue();
1670 if (LAddOpnd == RAddOpnd && DiffC.isPowerOf2()) {
1671 ConstantInt *MaxAddC = nullptr;
1672 if (LAddC->getValue().ult(RAddC->getValue()))
1673 MaxAddC = RAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001674 else
Sanjay Patel519a87a2017-04-05 17:38:34 +00001675 MaxAddC = LAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001676
Sanjay Patel519a87a2017-04-05 17:38:34 +00001677 APInt RRangeLow = -RAddC->getValue();
1678 APInt RRangeHigh = RRangeLow + LHSC->getValue();
1679 APInt LRangeLow = -LAddC->getValue();
1680 APInt LRangeHigh = LRangeLow + LHSC->getValue();
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001681 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1682 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1683 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1684 : RRangeLow - LRangeLow;
1685
1686 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
Sanjay Patel519a87a2017-04-05 17:38:34 +00001687 RangeDiff.ugt(LHSC->getValue())) {
1688 Value *MaskC = ConstantInt::get(LAddC->getType(), ~DiffC);
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001689
Sanjay Patel519a87a2017-04-05 17:38:34 +00001690 Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskC);
1691 Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddC);
1692 return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSC));
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001693 }
1694 }
1695 }
1696 }
1697
Chris Lattner0a8191e2010-01-05 07:50:36 +00001698 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001699 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001700 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1701 LHS->getOperand(1) == RHS->getOperand(0))
1702 LHS->swapOperands();
1703 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1704 LHS->getOperand(1) == RHS->getOperand(1)) {
1705 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1706 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1707 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001708 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001709 }
1710 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001711
1712 // handle (roughly):
1713 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001714 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001715 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001716
Sanjay Patele4159d22017-04-10 19:38:36 +00001717 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001718 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1719 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1720 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001721 Value *A = nullptr, *B = nullptr;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001722 if (PredL == ICmpInst::ICMP_EQ && LHSC && LHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001723 B = LHS0;
1724 if (PredR == ICmpInst::ICMP_ULT && LHS0 == RHS->getOperand(1))
1725 A = RHS0;
1726 else if (PredR == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001727 A = RHS->getOperand(1);
1728 }
1729 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1730 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001731 else if (PredR == ICmpInst::ICMP_EQ && RHSC && RHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001732 B = RHS0;
1733 if (PredL == ICmpInst::ICMP_ULT && RHS0 == LHS->getOperand(1))
1734 A = LHS0;
1735 else if (PredL == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001736 A = LHS->getOperand(1);
1737 }
1738 if (A && B)
1739 return Builder->CreateICmp(
1740 ICmpInst::ICMP_UGE,
1741 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1742 }
1743
Erik Ecksteind1817522014-12-03 10:39:15 +00001744 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1745 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1746 return V;
1747
1748 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1749 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1750 return V;
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001751
Sanjay Patelef9f5862017-04-15 17:55:06 +00001752 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, false, Builder))
1753 return V;
1754
David Majnemerc2a990b2013-07-05 00:31:17 +00001755 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001756 if (!LHSC || !RHSC)
1757 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001758
Sanjay Patel519a87a2017-04-05 17:38:34 +00001759 if (LHSC == RHSC && PredL == PredR) {
Owen Anderson8f306a72010-08-02 09:32:13 +00001760 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001761 if (PredL == ICmpInst::ICMP_NE && LHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001762 Value *NewOr = Builder->CreateOr(LHS0, RHS0);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001763 return Builder->CreateICmp(PredL, NewOr, LHSC);
Owen Anderson8f306a72010-08-02 09:32:13 +00001764 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001765 }
1766
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001767 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001768 // iff C2 + CA == C1.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001769 if (PredL == ICmpInst::ICMP_ULT && PredR == ICmpInst::ICMP_EQ) {
1770 ConstantInt *AddC;
Sanjay Patele4159d22017-04-10 19:38:36 +00001771 if (match(LHS0, m_Add(m_Specific(RHS0), m_ConstantInt(AddC))))
Sanjay Patel519a87a2017-04-05 17:38:34 +00001772 if (RHSC->getValue() + AddC->getValue() == LHSC->getValue())
Sanjay Patele4159d22017-04-10 19:38:36 +00001773 return Builder->CreateICmpULE(LHS0, LHSC);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001774 }
1775
Chris Lattner0a8191e2010-01-05 07:50:36 +00001776 // From here on, we only handle:
1777 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +00001778 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001779 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001780
Sanjay Patel519a87a2017-04-05 17:38:34 +00001781 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
1782 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
1783 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
1784 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
1785 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001786 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001787
Chris Lattner0a8191e2010-01-05 07:50:36 +00001788 // We can't fold (ugt x, C) | (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001789 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +00001790 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001791
Chris Lattner0a8191e2010-01-05 07:50:36 +00001792 // Ensure that the larger constant is on the RHS.
1793 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +00001794 if (CmpInst::isSigned(PredL) ||
1795 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +00001796 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +00001797 else
1798 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001799
Chris Lattner0a8191e2010-01-05 07:50:36 +00001800 if (ShouldSwap) {
1801 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001802 std::swap(LHSC, RHSC);
1803 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001804 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001805
Dan Gohman4a618822010-02-10 16:03:48 +00001806 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001807 // comparing a value against two constants and or'ing the result
1808 // together. Because of the above check, we know that we only have
1809 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1810 // icmp folding check above), that the two constants are not
1811 // equal.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001812 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001813
Sanjay Patel519a87a2017-04-05 17:38:34 +00001814 switch (PredL) {
1815 default:
1816 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001817 case ICmpInst::ICMP_EQ:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001818 switch (PredR) {
1819 default:
1820 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001821 case ICmpInst::ICMP_EQ:
Sanjay Patel7cfe4162017-04-14 19:23:50 +00001822 // Potential folds for this case should already be handled.
1823 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001824 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1825 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001826 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001827 }
1828 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001829 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001830 switch (PredR) {
1831 default:
1832 llvm_unreachable("Unknown integer condition code!");
1833 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001834 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001835 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001836 assert(!RHSC->isMaxValue(false) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001837 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1,
1838 false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001839 }
1840 break;
1841 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001842 switch (PredR) {
1843 default:
1844 llvm_unreachable("Unknown integer condition code!");
1845 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001846 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001847 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001848 assert(!RHSC->isMaxValue(true) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001849 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1, true,
Sanjay Patel519a87a2017-04-05 17:38:34 +00001850 false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001851 }
1852 break;
1853 }
Craig Topperf40110f2014-04-25 05:29:35 +00001854 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001855}
1856
Sanjay Patel18549272015-09-08 18:24:36 +00001857/// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
1858/// a Value which should already be inserted into the function.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001859Value *InstCombiner::foldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +00001860 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1861 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1862 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1863
1864 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1865 // Swap RHS operands to match LHS.
1866 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1867 std::swap(Op1LHS, Op1RHS);
1868 }
1869
1870 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1871 // This is a similar transformation to the one in FoldAndOfFCmps.
1872 //
1873 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1874 // bool(R & CC0) || bool(R & CC1)
1875 // = bool((R & CC0) | (R & CC1))
1876 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1877 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1878 return getFCmpValue(getFCmpCode(Op0CC) | getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1879 Builder);
1880
Chris Lattner0a8191e2010-01-05 07:50:36 +00001881 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00001882 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001883 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1884 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1885 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1886 // If either of the constants are nans, then the whole thing returns
1887 // true.
1888 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001889 return Builder->getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001890
Chris Lattner0a8191e2010-01-05 07:50:36 +00001891 // Otherwise, no need to compare the two constants, compare the
1892 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00001893 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001894 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001895
Chris Lattner0a8191e2010-01-05 07:50:36 +00001896 // Handle vector zeros. This occurs because the canonical form of
1897 // "fcmp uno x,x" is "fcmp uno x, 0".
1898 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1899 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001900 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00001901
Craig Topperf40110f2014-04-25 05:29:35 +00001902 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001903 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001904
Craig Topperf40110f2014-04-25 05:29:35 +00001905 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001906}
1907
Sanjay Patel18549272015-09-08 18:24:36 +00001908/// This helper function folds:
Chris Lattner0a8191e2010-01-05 07:50:36 +00001909///
1910/// ((A | B) & C1) | (B & C2)
1911///
1912/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00001913///
Chris Lattner0a8191e2010-01-05 07:50:36 +00001914/// (A & C1) | B
1915///
1916/// when the XOR of the two constants is "all ones" (-1).
Craig Toppera074c102017-06-21 18:57:00 +00001917static Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
1918 Value *A, Value *B, Value *C,
1919 InstCombiner::BuilderTy *Builder) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001920 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +00001921 if (!CI1) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001922
Craig Topperf40110f2014-04-25 05:29:35 +00001923 Value *V1 = nullptr;
1924 ConstantInt *CI2 = nullptr;
1925 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001926
1927 APInt Xor = CI1->getValue() ^ CI2->getValue();
Craig Topperf40110f2014-04-25 05:29:35 +00001928 if (!Xor.isAllOnesValue()) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001929
1930 if (V1 == A || V1 == B) {
1931 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1932 return BinaryOperator::CreateOr(NewOp, V1);
1933 }
1934
Craig Topperf40110f2014-04-25 05:29:35 +00001935 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001936}
1937
David Majnemer5d1aeba2014-08-21 05:14:48 +00001938/// \brief This helper function folds:
1939///
Craig Toppera074c102017-06-21 18:57:00 +00001940/// ((A ^ B) & C1) | (B & C2)
David Majnemer5d1aeba2014-08-21 05:14:48 +00001941///
1942/// into:
1943///
1944/// (A & C1) ^ B
1945///
1946/// when the XOR of the two constants is "all ones" (-1).
Craig Toppera074c102017-06-21 18:57:00 +00001947static Instruction *FoldXorWithConstants(BinaryOperator &I, Value *Op,
1948 Value *A, Value *B, Value *C,
1949 InstCombiner::BuilderTy *Builder) {
David Majnemer5d1aeba2014-08-21 05:14:48 +00001950 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1951 if (!CI1)
1952 return nullptr;
1953
1954 Value *V1 = nullptr;
1955 ConstantInt *CI2 = nullptr;
1956 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
1957 return nullptr;
1958
1959 APInt Xor = CI1->getValue() ^ CI2->getValue();
1960 if (!Xor.isAllOnesValue())
1961 return nullptr;
1962
1963 if (V1 == A || V1 == B) {
1964 Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
1965 return BinaryOperator::CreateXor(NewOp, V1);
1966 }
1967
1968 return nullptr;
1969}
1970
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001971// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1972// here. We should standardize that construct where it is needed or choose some
1973// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001974Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001975 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001976 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1977
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001978 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001979 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001980
Craig Toppera4205622017-06-09 03:21:29 +00001981 if (Value *V = SimplifyOrInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001982 return replaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00001983
Craig Topper9d4171a2012-12-20 07:09:41 +00001984 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001985 // purpose is to compute bits we don't care about.
1986 if (SimplifyDemandedInstructionBits(I))
1987 return &I;
1988
Sanjay Patele0c26e02017-04-23 22:00:02 +00001989 // Do this before using distributive laws to catch simple and/or/not patterns.
1990 if (Instruction *Xor = foldOrToXor(I, *Builder))
1991 return Xor;
1992
1993 // (A&B)|(A&C) -> A&(B|C) etc
1994 if (Value *V = SimplifyUsingDistributiveLaws(I))
1995 return replaceInstUsesWith(I, V);
1996
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001997 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001998 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001999
Craig Topper86173602017-04-04 20:26:25 +00002000 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00002001 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2002 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002003
Chad Rosiere5819e22016-05-26 14:58:51 +00002004 // Given an OR instruction, check to see if this is a bswap.
2005 if (Instruction *BSwap = MatchBSwap(I))
2006 return BSwap;
2007
Craig Topperafa07c52017-04-09 06:12:41 +00002008 {
2009 Value *A;
2010 const APInt *C;
2011 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2012 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
2013 MaskedValueIsZero(Op1, *C, 0, &I)) {
2014 Value *NOr = Builder->CreateOr(A, Op1);
2015 NOr->takeName(Op0);
2016 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00002017 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00002018 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002019
Craig Topperafa07c52017-04-09 06:12:41 +00002020 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2021 if (match(Op1, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
2022 MaskedValueIsZero(Op0, *C, 0, &I)) {
2023 Value *NOr = Builder->CreateOr(A, Op0);
2024 NOr->takeName(Op0);
2025 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00002026 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00002027 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002028 }
2029
Craig Topperafa07c52017-04-09 06:12:41 +00002030 Value *A, *B;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002031
Suyog Sardad64faf62014-07-22 18:09:41 +00002032 // ((~A & B) | A) -> (A | B)
Craig Topper72a622c2017-04-07 00:29:47 +00002033 if (match(Op0, m_c_And(m_Not(m_Specific(Op1)), m_Value(A))))
2034 return BinaryOperator::CreateOr(A, Op1);
2035 if (match(Op1, m_c_And(m_Not(m_Specific(Op0)), m_Value(A))))
2036 return BinaryOperator::CreateOr(Op0, A);
Suyog Sardad64faf62014-07-22 18:09:41 +00002037
2038 // ((A & B) | ~A) -> (~A | B)
Craig Topper33e0dbc2017-04-07 07:32:00 +00002039 // The NOT is guaranteed to be in the RHS by complexity ordering.
2040 if (match(Op1, m_Not(m_Value(A))) &&
2041 match(Op0, m_c_And(m_Specific(A), m_Value(B))))
2042 return BinaryOperator::CreateOr(Op1, B);
Suyog Sardad64faf62014-07-22 18:09:41 +00002043
Chris Lattner0a8191e2010-01-05 07:50:36 +00002044 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00002045 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002046 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2047 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperf40110f2014-04-25 05:29:35 +00002048 Value *V1 = nullptr, *V2 = nullptr;
Craig Topperafa07c52017-04-09 06:12:41 +00002049 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
2050 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002051 if (C1 && C2) { // (A & C1)|(B & C2)
Craig Topper73ba1c82017-06-07 07:40:37 +00002052 if ((C1->getValue() & C2->getValue()).isNullValue()) {
Chris Lattner95188692010-01-11 06:55:24 +00002053 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002054 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002055 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002056 ((V1 == B &&
2057 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2058 (V2 == B &&
2059 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002060 return BinaryOperator::CreateAnd(A,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002061 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002062 // Or commutes, try both ways.
2063 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002064 ((V1 == A &&
2065 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2066 (V2 == A &&
2067 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002068 return BinaryOperator::CreateAnd(B,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002069 Builder->getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002070
Chris Lattner95188692010-01-11 06:55:24 +00002071 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002072 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00002073 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00002074 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00002075 (C3->getValue() & ~C1->getValue()).isNullValue() &&
Chris Lattner95188692010-01-11 06:55:24 +00002076 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00002077 (C4->getValue() & ~C2->getValue()).isNullValue()) {
Chris Lattner95188692010-01-11 06:55:24 +00002078 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2079 return BinaryOperator::CreateAnd(V2,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002080 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002081 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002082 }
2083 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002084
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002085 // Don't try to form a select if it's unlikely that we'll get rid of at
2086 // least one of the operands. A select is generally more expensive than the
2087 // 'or' that it is replacing.
2088 if (Op0->hasOneUse() || Op1->hasOneUse()) {
2089 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
2090 if (Value *V = matchSelectFromAndOr(A, C, B, D, *Builder))
2091 return replaceInstUsesWith(I, V);
2092 if (Value *V = matchSelectFromAndOr(A, C, D, B, *Builder))
2093 return replaceInstUsesWith(I, V);
2094 if (Value *V = matchSelectFromAndOr(C, A, B, D, *Builder))
2095 return replaceInstUsesWith(I, V);
2096 if (Value *V = matchSelectFromAndOr(C, A, D, B, *Builder))
2097 return replaceInstUsesWith(I, V);
2098 if (Value *V = matchSelectFromAndOr(B, D, A, C, *Builder))
2099 return replaceInstUsesWith(I, V);
2100 if (Value *V = matchSelectFromAndOr(B, D, C, A, *Builder))
2101 return replaceInstUsesWith(I, V);
2102 if (Value *V = matchSelectFromAndOr(D, B, A, C, *Builder))
2103 return replaceInstUsesWith(I, V);
2104 if (Value *V = matchSelectFromAndOr(D, B, C, A, *Builder))
2105 return replaceInstUsesWith(I, V);
2106 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002107
Benjamin Kramer11743242010-07-12 13:34:22 +00002108 // ((A|B)&1)|(B&-2) -> (A&1) | B
Craig Toppera074c102017-06-21 18:57:00 +00002109 if (match(A, m_c_Or(m_Value(V1), m_Specific(B)))) {
2110 if (Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C, Builder))
2111 return Ret;
Benjamin Kramer11743242010-07-12 13:34:22 +00002112 }
2113 // (B&-2)|((A|B)&1) -> (A&1) | B
Craig Toppera074c102017-06-21 18:57:00 +00002114 if (match(B, m_c_Or(m_Specific(A), m_Value(V1)))) {
2115 if (Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D, Builder))
2116 return Ret;
Benjamin Kramer11743242010-07-12 13:34:22 +00002117 }
David Majnemer5d1aeba2014-08-21 05:14:48 +00002118 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
Craig Toppera074c102017-06-21 18:57:00 +00002119 if (match(A, m_c_Xor(m_Value(V1), m_Specific(B)))) {
2120 if (Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C, Builder))
2121 return Ret;
David Majnemer5d1aeba2014-08-21 05:14:48 +00002122 }
2123 // (B&-2)|((A^B)&1) -> (A&1) ^ B
Craig Toppera074c102017-06-21 18:57:00 +00002124 if (match(B, m_c_Xor(m_Specific(A), m_Value(V1)))) {
2125 if (Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D, Builder))
2126 return Ret;
David Majnemer5d1aeba2014-08-21 05:14:48 +00002127 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002128 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002129
David Majnemer42af3602014-07-30 21:26:37 +00002130 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2131 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2132 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00002133 return BinaryOperator::CreateOr(Op0, C);
David Majnemer42af3602014-07-30 21:26:37 +00002134
2135 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2136 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2137 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00002138 return BinaryOperator::CreateOr(Op1, C);
David Majnemer42af3602014-07-30 21:26:37 +00002139
David Majnemerf1eda232014-08-14 06:41:38 +00002140 // ((B | C) & A) | B -> B | (A & C)
2141 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2142 return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2143
Sanjay Patel7caaa792017-05-09 20:05:05 +00002144 if (Instruction *DeMorgan = matchDeMorgansLaws(I, *Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00002145 return DeMorgan;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002146
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002147 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002148 bool SwappedForXor = false;
2149 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002150 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002151 SwappedForXor = true;
2152 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002153
2154 // A | ( A ^ B) -> A | B
2155 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002156 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002157 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2158 if (Op0 == A || Op0 == B)
2159 return BinaryOperator::CreateOr(A, B);
2160
Chad Rosier7813dce2012-04-26 23:29:14 +00002161 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2162 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2163 return BinaryOperator::CreateOr(A, B);
2164
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002165 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2166 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2167 return BinaryOperator::CreateOr(Not, Op0);
2168 }
2169 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2170 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2171 return BinaryOperator::CreateOr(Not, Op0);
2172 }
2173 }
2174
2175 // A | ~(A | B) -> A | ~B
2176 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002177 if (match(Op1, m_Not(m_Value(A))))
2178 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002179 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2180 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2181 B->getOpcode() == Instruction::Xor)) {
2182 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2183 B->getOperand(0);
2184 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2185 return BinaryOperator::CreateOr(Not, Op0);
2186 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002187
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002188 // (A & B) | (~A ^ B) -> (~A ^ B)
2189 // (A & B) | (B ^ ~A) -> (~A ^ B)
2190 // (B & A) | (~A ^ B) -> (~A ^ B)
2191 // (B & A) | (B ^ ~A) -> (~A ^ B)
2192 // The match order is important: match the xor first because the 'not'
2193 // operation defines 'A'. We do not need to match the xor as Op0 because the
2194 // xor was canonicalized to Op1 above.
2195 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2196 match(Op0, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sarda16d64652014-08-01 04:41:43 +00002197 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2198
Eli Friedmane06535b2012-03-16 00:52:42 +00002199 if (SwappedForXor)
2200 std::swap(Op0, Op1);
2201
David Majnemer3d6f80b2014-11-28 19:58:29 +00002202 {
2203 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2204 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2205 if (LHS && RHS)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002206 if (Value *Res = foldOrOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002207 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002208
David Majnemer3d6f80b2014-11-28 19:58:29 +00002209 // TODO: Make this recursive; it's a little tricky because an arbitrary
2210 // number of 'or' instructions might have to be created.
2211 Value *X, *Y;
2212 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2213 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002214 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002215 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002216 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002217 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002218 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002219 }
2220 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2221 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002222 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002223 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002224 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002225 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002226 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002227 }
2228 }
2229
Chris Lattner4e8137d2010-02-11 06:26:33 +00002230 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2231 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2232 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel5e456b92017-05-18 20:53:16 +00002233 if (Value *Res = foldOrOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00002234 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002235
Sanjay Patel75b4ae22016-02-23 23:56:23 +00002236 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2237 return CastedOr;
Eli Friedman23956262011-04-14 22:41:27 +00002238
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002239 // 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 +00002240 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002241 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002242 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
Sanjay Patel1b6b8242016-07-08 17:26:47 +00002243 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002244 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002245 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2246
Owen Andersonc237a842010-09-13 17:59:27 +00002247 // Note: If we've gotten to the point of visiting the outer OR, then the
2248 // inner one couldn't be simplified. If it was a constant, then it won't
2249 // be simplified by a later pass either, so we try swapping the inner/outer
2250 // ORs in the hopes that we'll be able to simplify it this way.
2251 // (X|C) | V --> (X|V) | C
Craig Topperafa07c52017-04-09 06:12:41 +00002252 ConstantInt *C1;
Owen Andersonc237a842010-09-13 17:59:27 +00002253 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2254 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2255 Value *Inner = Builder->CreateOr(A, Op1);
2256 Inner->takeName(Op0);
2257 return BinaryOperator::CreateOr(Inner, C1);
2258 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002259
Bill Wendling23242092013-02-16 23:41:36 +00002260 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2261 // Since this OR statement hasn't been optimized further yet, we hope
2262 // that this transformation will allow the new ORs to be optimized.
2263 {
Craig Topperf40110f2014-04-25 05:29:35 +00002264 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002265 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2266 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2267 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2268 Value *orTrue = Builder->CreateOr(A, C);
2269 Value *orFalse = Builder->CreateOr(B, D);
2270 return SelectInst::Create(X, orTrue, orFalse);
2271 }
2272 }
2273
Craig Topperf40110f2014-04-25 05:29:35 +00002274 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002275}
2276
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002277/// A ^ B can be specified using other logic ops in a variety of patterns. We
2278/// can fold these early and efficiently by morphing an existing instruction.
2279static Instruction *foldXorToXor(BinaryOperator &I) {
2280 assert(I.getOpcode() == Instruction::Xor);
2281 Value *Op0 = I.getOperand(0);
2282 Value *Op1 = I.getOperand(1);
2283 Value *A, *B;
2284
2285 // There are 4 commuted variants for each of the basic patterns.
2286
2287 // (A & B) ^ (A | B) -> A ^ B
2288 // (A & B) ^ (B | A) -> A ^ B
2289 // (A | B) ^ (A & B) -> A ^ B
2290 // (A | B) ^ (B & A) -> A ^ B
2291 if ((match(Op0, m_And(m_Value(A), m_Value(B))) &&
2292 match(Op1, m_c_Or(m_Specific(A), m_Specific(B)))) ||
2293 (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2294 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))) {
2295 I.setOperand(0, A);
2296 I.setOperand(1, B);
2297 return &I;
2298 }
2299
2300 // (A | ~B) ^ (~A | B) -> A ^ B
2301 // (~B | A) ^ (~A | B) -> A ^ B
2302 // (~A | B) ^ (A | ~B) -> A ^ B
2303 // (B | ~A) ^ (A | ~B) -> A ^ B
2304 if ((match(Op0, m_c_Or(m_Value(A), m_Not(m_Value(B)))) &&
2305 match(Op1, m_Or(m_Not(m_Specific(A)), m_Specific(B)))) ||
2306 (match(Op0, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
2307 match(Op1, m_Or(m_Specific(A), m_Not(m_Specific(B)))))) {
2308 I.setOperand(0, A);
2309 I.setOperand(1, B);
2310 return &I;
2311 }
2312
2313 // (A & ~B) ^ (~A & B) -> A ^ B
2314 // (~B & A) ^ (~A & B) -> A ^ B
2315 // (~A & B) ^ (A & ~B) -> A ^ B
2316 // (B & ~A) ^ (A & ~B) -> A ^ B
2317 if ((match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
2318 match(Op1, m_And(m_Not(m_Specific(A)), m_Specific(B)))) ||
2319 (match(Op0, m_c_And(m_Not(m_Value(A)), m_Value(B))) &&
2320 match(Op1, m_And(m_Specific(A), m_Not(m_Specific(B)))))) {
2321 I.setOperand(0, A);
2322 I.setOperand(1, B);
2323 return &I;
2324 }
2325
2326 return nullptr;
2327}
2328
Sanjay Patel5e456b92017-05-18 20:53:16 +00002329Value *InstCombiner::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
2330 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2331 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2332 LHS->getOperand(1) == RHS->getOperand(0))
2333 LHS->swapOperands();
2334 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2335 LHS->getOperand(1) == RHS->getOperand(1)) {
2336 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2337 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2338 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2339 bool isSigned = LHS->isSigned() || RHS->isSigned();
2340 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
2341 }
2342 }
2343
Sanjay Pateladca8252017-06-20 12:40:55 +00002344 // Instead of trying to imitate the folds for and/or, decompose this 'xor'
2345 // into those logic ops. That is, try to turn this into an and-of-icmps
2346 // because we have many folds for that pattern.
2347 //
2348 // This is based on a truth table definition of xor:
2349 // X ^ Y --> (X | Y) & !(X & Y)
2350 if (Value *OrICmp = SimplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
2351 // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
2352 // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
2353 if (Value *AndICmp = SimplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
2354 // TODO: Independently handle cases where the 'and' side is a constant.
2355 if (OrICmp == LHS && AndICmp == RHS && RHS->hasOneUse()) {
2356 // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS
2357 RHS->setPredicate(RHS->getInversePredicate());
2358 return Builder->CreateAnd(LHS, RHS);
2359 }
2360 if (OrICmp == RHS && AndICmp == LHS && LHS->hasOneUse()) {
Sanjay Patel4ccbd582017-06-20 12:45:46 +00002361 // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS
Sanjay Pateladca8252017-06-20 12:40:55 +00002362 LHS->setPredicate(LHS->getInversePredicate());
2363 return Builder->CreateAnd(LHS, RHS);
2364 }
2365 }
2366 }
2367
Sanjay Patel5e456b92017-05-18 20:53:16 +00002368 return nullptr;
2369}
2370
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002371// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2372// here. We should standardize that construct where it is needed or choose some
2373// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002374Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002375 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002376 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2377
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002378 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002379 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002380
Craig Toppera4205622017-06-09 03:21:29 +00002381 if (Value *V = SimplifyXorInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002382 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002383
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002384 if (Instruction *NewXor = foldXorToXor(I))
2385 return NewXor;
2386
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002387 // (A&B)^(A&C) -> A&(B^C) etc
2388 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002389 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002390
Craig Topper9d4171a2012-12-20 07:09:41 +00002391 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002392 // purpose is to compute bits we don't care about.
2393 if (SimplifyDemandedInstructionBits(I))
2394 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002395
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002396 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002397 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002398
Sanjay Patel6381db12017-05-02 15:31:40 +00002399 // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
2400 Value *X, *Y;
2401
2402 // We must eliminate the and/or (one-use) for these transforms to not increase
2403 // the instruction count.
2404 // ~(~X & Y) --> (X | ~Y)
2405 // ~(Y & ~X) --> (X | ~Y)
2406 if (match(&I, m_Not(m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y)))))) {
2407 Value *NotY = Builder->CreateNot(Y, Y->getName() + ".not");
2408 return BinaryOperator::CreateOr(X, NotY);
2409 }
2410 // ~(~X | Y) --> (X & ~Y)
2411 // ~(Y | ~X) --> (X & ~Y)
2412 if (match(&I, m_Not(m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y)))))) {
2413 Value *NotY = Builder->CreateNot(Y, Y->getName() + ".not");
2414 return BinaryOperator::CreateAnd(X, NotY);
2415 }
2416
Sanjay Patel3b863f82017-04-22 18:05:35 +00002417 // Is this a 'not' (~) fed by a binary operator?
Sanjay Patela1c88142017-05-08 20:49:59 +00002418 BinaryOperator *NotVal;
2419 if (match(&I, m_Not(m_BinOp(NotVal)))) {
2420 if (NotVal->getOpcode() == Instruction::And ||
2421 NotVal->getOpcode() == Instruction::Or) {
Sanjay Patel6381db12017-05-02 15:31:40 +00002422 // Apply DeMorgan's Law when inverts are free:
2423 // ~(X & Y) --> (~X | ~Y)
2424 // ~(X | Y) --> (~X & ~Y)
Sanjay Patela1c88142017-05-08 20:49:59 +00002425 if (IsFreeToInvert(NotVal->getOperand(0),
2426 NotVal->getOperand(0)->hasOneUse()) &&
2427 IsFreeToInvert(NotVal->getOperand(1),
2428 NotVal->getOperand(1)->hasOneUse())) {
2429 Value *NotX = Builder->CreateNot(NotVal->getOperand(0), "notlhs");
2430 Value *NotY = Builder->CreateNot(NotVal->getOperand(1), "notrhs");
2431 if (NotVal->getOpcode() == Instruction::And)
Sanjay Patel3b863f82017-04-22 18:05:35 +00002432 return BinaryOperator::CreateOr(NotX, NotY);
2433 return BinaryOperator::CreateAnd(NotX, NotY);
2434 }
Sanjay Patela1c88142017-05-08 20:49:59 +00002435 }
2436
2437 // ~(~X >>s Y) --> (X >>s Y)
2438 if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
2439 return BinaryOperator::CreateAShr(X, Y);
2440
2441 // If we are inverting a right-shifted constant, we may be able to eliminate
2442 // the 'not' by inverting the constant and using the opposite shift type.
2443 // Canonicalization rules ensure that only a negative constant uses 'ashr',
2444 // but we must check that in case that transform has not fired yet.
2445 const APInt *C;
2446 if (match(NotVal, m_AShr(m_APInt(C), m_Value(Y))) && C->isNegative()) {
2447 // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
2448 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2449 return BinaryOperator::CreateLShr(NotC, Y);
2450 }
2451
2452 if (match(NotVal, m_LShr(m_APInt(C), m_Value(Y))) && C->isNonNegative()) {
2453 // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
2454 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2455 return BinaryOperator::CreateAShr(NotC, Y);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002456 }
2457 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002458
Craig Topper798a19a2017-06-29 00:07:08 +00002459 // not (cmp A, B) = !cmp A, B
Sanjay Patel33439f92017-04-12 15:11:33 +00002460 ICmpInst::Predicate Pred;
Craig Topper798a19a2017-06-29 00:07:08 +00002461 if (match(&I, m_Not(m_OneUse(m_Cmp(Pred, m_Value(), m_Value()))))) {
Sanjay Patel33439f92017-04-12 15:11:33 +00002462 cast<CmpInst>(Op0)->setPredicate(CmpInst::getInversePredicate(Pred));
2463 return replaceInstUsesWith(I, Op0);
Benjamin Kramer443c7962015-02-12 20:26:46 +00002464 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002465
Craig Topper9d1821b2017-04-09 06:12:31 +00002466 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002467 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2468 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2469 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2470 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2471 Instruction::CastOps Opcode = Op0C->getOpcode();
2472 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Craig Topper9d1821b2017-04-09 06:12:31 +00002473 (RHSC == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Chris Lattner0a8191e2010-01-05 07:50:36 +00002474 Op0C->getDestTy()))) {
2475 CI->setPredicate(CI->getInversePredicate());
2476 return CastInst::Create(Opcode, CI, Op0C->getType());
2477 }
2478 }
2479 }
2480 }
2481
2482 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2483 // ~(c-X) == X-c-1 == X+(-c-1)
Craig Topper9d1821b2017-04-09 06:12:31 +00002484 if (Op0I->getOpcode() == Instruction::Sub && RHSC->isAllOnesValue())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002485 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2486 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
Craig Topper437c9762017-04-09 06:12:34 +00002487 return BinaryOperator::CreateAdd(Op0I->getOperand(1),
2488 SubOne(NegOp0I0C));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002489 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002490
Chris Lattner0a8191e2010-01-05 07:50:36 +00002491 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2492 if (Op0I->getOpcode() == Instruction::Add) {
2493 // ~(X-c) --> (-c-1)-X
Craig Topper9d1821b2017-04-09 06:12:31 +00002494 if (RHSC->isAllOnesValue()) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002495 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Craig Topper437c9762017-04-09 06:12:34 +00002496 return BinaryOperator::CreateSub(SubOne(NegOp0CI),
2497 Op0I->getOperand(0));
Craig Topperbcfd2d12017-04-20 16:56:25 +00002498 } else if (RHSC->getValue().isSignMask()) {
2499 // (X + C) ^ signmask -> (X + C + signmask)
Craig Topper9d1821b2017-04-09 06:12:31 +00002500 Constant *C = Builder->getInt(RHSC->getValue() + Op0CI->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002501 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2502
2503 }
2504 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002505 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Hal Finkel60db0582014-09-07 18:57:58 +00002506 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2507 0, &I)) {
Craig Topper9d1821b2017-04-09 06:12:31 +00002508 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002509 // Anything in both C1 and C2 is known to be zero, remove it from
2510 // NewRHS.
Craig Topper9d1821b2017-04-09 06:12:31 +00002511 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHSC);
Craig Topper9d4171a2012-12-20 07:09:41 +00002512 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002513 ConstantExpr::getNot(CommonBits));
2514 Worklist.Add(Op0I);
2515 I.setOperand(0, Op0I->getOperand(0));
2516 I.setOperand(1, NewRHS);
2517 return &I;
2518 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002519 } else if (Op0I->getOpcode() == Instruction::LShr) {
2520 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2521 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002522 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002523 ConstantInt *C1;
2524 if (Op0I->hasOneUse() &&
2525 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2526 E1->getOpcode() == Instruction::Xor &&
2527 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2528 // fold (C1 >> C2) ^ C3
Craig Topper9d1821b2017-04-09 06:12:31 +00002529 ConstantInt *C2 = Op0CI, *C3 = RHSC;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002530 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2531 FoldConst ^= C3->getValue();
2532 // Prepare the two operands.
2533 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2534 Opnd0->takeName(Op0I);
2535 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2536 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2537
2538 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2539 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002540 }
2541 }
2542 }
Craig Topper86173602017-04-04 20:26:25 +00002543 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002544
Craig Topper86173602017-04-04 20:26:25 +00002545 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00002546 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2547 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002548
Craig Topper76394602017-04-10 06:53:23 +00002549 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002550 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002551 if (match(Op1, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Craig Topper47383212017-04-10 06:53:21 +00002552 if (A == Op0) { // A^(A|B) == A^(B|A)
Craig Topper76394602017-04-10 06:53:23 +00002553 cast<BinaryOperator>(Op1)->swapOperands();
Craig Topper47383212017-04-10 06:53:21 +00002554 std::swap(A, B);
2555 }
2556 if (B == Op0) { // A^(B|A) == (B|A)^A
Chris Lattner0a8191e2010-01-05 07:50:36 +00002557 I.swapOperands(); // Simplified below.
2558 std::swap(Op0, Op1);
2559 }
Craig Topper76394602017-04-10 06:53:23 +00002560 } else if (match(Op1, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002561 if (A == Op0) { // A^(A&B) -> A^(B&A)
Craig Topper76394602017-04-10 06:53:23 +00002562 cast<BinaryOperator>(Op1)->swapOperands();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002563 std::swap(A, B);
2564 }
2565 if (B == Op0) { // A^(B&A) -> (B&A)^A
2566 I.swapOperands(); // Simplified below.
2567 std::swap(Op0, Op1);
2568 }
2569 }
2570 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002571
Craig Topper76394602017-04-10 06:53:23 +00002572 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002573 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002574 if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002575 if (A == Op1) // (B|A)^B == (A|B)^B
2576 std::swap(A, B);
2577 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002578 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper76394602017-04-10 06:53:23 +00002579 } else if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002580 if (A == Op1) // (A&B)^A -> (B&A)^A
2581 std::swap(A, B);
Craig Toppere63c21b2017-04-09 06:12:39 +00002582 const APInt *C;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002583 if (B == Op1 && // (B&A)^A == ~B & A
Craig Toppere63c21b2017-04-09 06:12:39 +00002584 !match(Op1, m_APInt(C))) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002585 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002586 }
2587 }
2588 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002589
Craig Topper76394602017-04-10 06:53:23 +00002590 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002591 Value *A, *B, *C, *D;
David Majnemer6fe6ea72014-09-05 06:09:24 +00002592 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002593 if (match(Op0, m_Xor(m_Value(D), m_Value(C))) &&
2594 match(Op1, m_Or(m_Value(A), m_Value(B)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002595 if (D == A)
2596 return BinaryOperator::CreateXor(
2597 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2598 if (D == B)
2599 return BinaryOperator::CreateXor(
2600 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002601 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002602 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002603 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2604 match(Op1, m_Xor(m_Value(D), m_Value(C)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002605 if (D == A)
2606 return BinaryOperator::CreateXor(
2607 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2608 if (D == B)
2609 return BinaryOperator::CreateXor(
2610 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002611 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002612 // (A & B) ^ (A ^ B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002613 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002614 match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002615 return BinaryOperator::CreateOr(A, B);
2616 // (A ^ B) ^ (A & B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002617 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002618 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002619 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002620 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002621
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002622 // (A & ~B) ^ ~A -> ~(A & B)
2623 // (~B & A) ^ ~A -> ~(A & B)
2624 Value *A, *B;
2625 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
Suyog Sarda56c9a872014-08-01 05:07:20 +00002626 match(Op1, m_Not(m_Specific(A))))
2627 return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2628
Sanjay Patel5e456b92017-05-18 20:53:16 +00002629 if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2630 if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2631 if (Value *V = foldXorOfICmps(LHS, RHS))
2632 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002633
Sanjay Pateldbbaca02016-02-24 17:00:34 +00002634 if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2635 return CastedXor;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002636
Craig Topperf40110f2014-04-25 05:29:35 +00002637 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002638}