blob: 7e8c2e1b4c1ddfc12533cb3c395f570b036f2cc0 [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
Craig Topperfc42ace2017-07-06 16:24:22 +000078/// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) or
79/// BITWISE_OP(BSWAP(A), Constant) to BSWAP(BITWISE_OP(A, B))
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000080/// \param I Binary operator to transform.
81/// \return Pointer to node that must replace the original binary operator, or
82/// null pointer if no transformation was made.
83Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
Craig Topperc6948c22017-07-03 05:54:11 +000084 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bswap simplifying");
85
Craig Topper22795de2017-07-06 16:24:21 +000086 Value *OldLHS = I.getOperand(0);
87 Value *OldRHS = I.getOperand(1);
Craig Topper80369702017-07-03 05:54:16 +000088
Craig Topper766ce6e2017-07-03 05:54:15 +000089 Value *NewLHS;
Craig Topper22795de2017-07-06 16:24:21 +000090 if (!match(OldLHS, m_BSwap(m_Value(NewLHS))))
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000091 return nullptr;
92
Craig Topper766ce6e2017-07-03 05:54:15 +000093 Value *NewRHS;
94 const APInt *C;
95
Craig Topper22795de2017-07-06 16:24:21 +000096 if (match(OldRHS, m_BSwap(m_Value(NewRHS)))) {
Craig Topper766ce6e2017-07-03 05:54:15 +000097 // OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
Craig Topper22795de2017-07-06 16:24:21 +000098 if (!OldLHS->hasOneUse() && !OldRHS->hasOneUse())
99 return nullptr;
Craig Topper766ce6e2017-07-03 05:54:15 +0000100 // NewRHS initialized by the matcher.
Craig Topper22795de2017-07-06 16:24:21 +0000101 } else if (match(OldRHS, m_APInt(C))) {
Craig Topper766ce6e2017-07-03 05:54:15 +0000102 // OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
Craig Topper22795de2017-07-06 16:24:21 +0000103 if (!OldLHS->hasOneUse())
104 return nullptr;
Craig Topper766ce6e2017-07-03 05:54:15 +0000105 NewRHS = ConstantInt::get(I.getType(), C->byteSwap());
106 } else
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000107 return nullptr;
108
Sanjay Patel1e6ca442016-11-22 22:54:36 +0000109 Value *BinOp = Builder->CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
Craig Topper1e4643a2017-07-03 05:54:13 +0000110 Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap,
111 I.getType());
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000112 return Builder->CreateCall(F, BinOp);
113}
114
Sanjay Patel18549272015-09-08 18:24:36 +0000115/// This handles expressions of the form ((val OP C1) & C2). Where
Craig Topper70e4f432017-04-02 17:57:30 +0000116/// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.
117Instruction *InstCombiner::OptAndOp(BinaryOperator *Op,
Chris Lattner0a8191e2010-01-05 07:50:36 +0000118 ConstantInt *OpRHS,
119 ConstantInt *AndRHS,
120 BinaryOperator &TheAnd) {
121 Value *X = Op->getOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +0000122 Constant *Together = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000123 if (!Op->isShift())
124 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
125
126 switch (Op->getOpcode()) {
Craig Topper70e4f432017-04-02 17:57:30 +0000127 default: break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000128 case Instruction::Xor:
129 if (Op->hasOneUse()) {
130 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
131 Value *And = Builder->CreateAnd(X, AndRHS);
132 And->takeName(Op);
133 return BinaryOperator::CreateXor(And, Together);
134 }
135 break;
136 case Instruction::Or:
Owen Andersonc237a842010-09-13 17:59:27 +0000137 if (Op->hasOneUse()){
Owen Andersonc237a842010-09-13 17:59:27 +0000138 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
139 if (TogetherCI && !TogetherCI->isZero()){
140 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
141 // NOTE: This reduces the number of bits set in the & mask, which
142 // can expose opportunities for store narrowing.
143 Together = ConstantExpr::getXor(AndRHS, Together);
144 Value *And = Builder->CreateAnd(X, Together);
145 And->takeName(Op);
146 return BinaryOperator::CreateOr(And, OpRHS);
147 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000148 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000149
Chris Lattner0a8191e2010-01-05 07:50:36 +0000150 break;
151 case Instruction::Add:
152 if (Op->hasOneUse()) {
153 // Adding a one to a single bit bit-field should be turned into an XOR
154 // of the bit. First thing to check is to see if this AND is with a
155 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000156 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000157
158 // If there is only one bit set.
159 if (AndRHSV.isPowerOf2()) {
160 // Ok, at this point, we know that we are masking the result of the
161 // ADD down to exactly one bit. If the constant we are adding has
162 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000163 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000164
165 // Check to see if any bits below the one bit set in AndRHSV are set.
Craig Topper73ba1c82017-06-07 07:40:37 +0000166 if ((AddRHS & (AndRHSV - 1)).isNullValue()) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000167 // If not, the only thing that can effect the output of the AND is
168 // the bit specified by AndRHSV. If that bit is set, the effect of
169 // the XOR is to toggle the bit. If it is clear, then the ADD has
170 // no effect.
Craig Topper73ba1c82017-06-07 07:40:37 +0000171 if ((AddRHS & AndRHSV).isNullValue()) { // Bit is not set, noop
Chris Lattner0a8191e2010-01-05 07:50:36 +0000172 TheAnd.setOperand(0, X);
173 return &TheAnd;
174 } else {
175 // Pull the XOR out of the AND.
176 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
177 NewAnd->takeName(Op);
178 return BinaryOperator::CreateXor(NewAnd, AndRHS);
179 }
180 }
181 }
182 }
183 break;
184
185 case Instruction::Shl: {
186 // We know that the AND will not produce any of the bits shifted in, so if
187 // the anded constant includes them, clear them now!
188 //
189 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
190 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
191 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000192 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000193
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000194 if (CI->getValue() == ShlMask)
195 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000196 return replaceInstUsesWith(TheAnd, Op); // No need for the and.
Craig Topper9d4171a2012-12-20 07:09:41 +0000197
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000198 if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000199 TheAnd.setOperand(1, CI);
200 return &TheAnd;
201 }
202 break;
203 }
204 case Instruction::LShr: {
205 // We know that the AND will not produce any of the bits shifted in, so if
206 // the anded constant includes them, clear them now! This only applies to
207 // unsigned shifts, because a signed shr may bring in set bits!
208 //
209 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
210 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
211 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000212 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000213
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000214 if (CI->getValue() == ShrMask)
215 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000216 return replaceInstUsesWith(TheAnd, Op);
Craig Topper9d4171a2012-12-20 07:09:41 +0000217
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000218 if (CI != AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000219 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
220 return &TheAnd;
221 }
222 break;
223 }
224 case Instruction::AShr:
225 // Signed shr.
226 // See if this is shifting in some sign extension, then masking it out
227 // with an and.
228 if (Op->hasOneUse()) {
229 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
230 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
231 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000232 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000233 if (C == AndRHS) { // Masking out bits shifted in.
234 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
235 // Make the argument unsigned.
236 Value *ShVal = Op->getOperand(0);
237 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
238 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
239 }
240 }
241 break;
242 }
Craig Topperf40110f2014-04-25 05:29:35 +0000243 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000244}
245
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000246/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000247/// (V < Lo || V >= Hi). This method expects that Lo <= Hi. IsSigned indicates
248/// whether to treat V, Lo, and Hi as signed or not.
Sanjay Patel85d79742016-08-31 19:49:56 +0000249Value *InstCombiner::insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
Chris Lattner067459c2010-03-05 08:46:26 +0000250 bool isSigned, bool Inside) {
Sanjay Patel85d79742016-08-31 19:49:56 +0000251 assert((isSigned ? Lo.sle(Hi) : Lo.ule(Hi)) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000252 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000253
Sanjay Patel85d79742016-08-31 19:49:56 +0000254 Type *Ty = V->getType();
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000255 if (Lo == Hi)
Sanjay Patel85d79742016-08-31 19:49:56 +0000256 return Inside ? ConstantInt::getFalse(Ty) : ConstantInt::getTrue(Ty);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000257
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000258 // V >= Min && V < Hi --> V < Hi
259 // V < Min || V >= Hi --> V >= Hi
260 ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
Sanjay Patel85d79742016-08-31 19:49:56 +0000261 if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000262 Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
Sanjay Patel85d79742016-08-31 19:49:56 +0000263 return Builder->CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000264 }
265
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000266 // V >= Lo && V < Hi --> V - Lo u< Hi - Lo
267 // V < Lo || V >= Hi --> V - Lo u>= Hi - Lo
Sanjay Patel85d79742016-08-31 19:49:56 +0000268 Value *VMinusLo =
269 Builder->CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
270 Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000271 return Builder->CreateICmp(Pred, VMinusLo, HiMinusLo);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000272}
273
Sanjay Patel77bf6222017-04-03 16:53:12 +0000274/// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
275/// that can be simplified.
276/// One of A and B is considered the mask. The other is the value. This is
277/// described as the "AMask" or "BMask" part of the enum. If the enum contains
278/// only "Mask", then both A and B can be considered masks. If A is the mask,
279/// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
280/// If both A and C are constants, this proof is also easy.
281/// For the following explanations, we assume that A is the mask.
282///
283/// "AllOnes" declares that the comparison is true only if (A & B) == A or all
284/// bits of A are set in B.
285/// Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
286///
287/// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
288/// bits of A are cleared in B.
289/// Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
290///
291/// "Mixed" declares that (A & B) == C and C might or might not contain any
292/// number of one bits and zero bits.
293/// Example: (icmp eq (A & 3), 1) -> AMask_Mixed
294///
295/// "Not" means that in above descriptions "==" should be replaced by "!=".
296/// Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
297///
Owen Anderson3fe002d2010-09-08 22:16:17 +0000298/// If the mask A contains a single bit, then the following is equivalent:
299/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
300/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
301enum MaskedICmpType {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000302 AMask_AllOnes = 1,
303 AMask_NotAllOnes = 2,
304 BMask_AllOnes = 4,
305 BMask_NotAllOnes = 8,
306 Mask_AllZeros = 16,
307 Mask_NotAllZeros = 32,
308 AMask_Mixed = 64,
309 AMask_NotMixed = 128,
310 BMask_Mixed = 256,
311 BMask_NotMixed = 512
Owen Anderson3fe002d2010-09-08 22:16:17 +0000312};
313
Sanjay Patel77bf6222017-04-03 16:53:12 +0000314/// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
315/// satisfies.
316static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
317 ICmpInst::Predicate Pred) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000318 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
319 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
320 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000321 bool IsEq = (Pred == ICmpInst::ICMP_EQ);
322 bool IsAPow2 = (ACst && !ACst->isZero() && ACst->getValue().isPowerOf2());
323 bool IsBPow2 = (BCst && !BCst->isZero() && BCst->getValue().isPowerOf2());
324 unsigned MaskVal = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000325 if (CCst && CCst->isZero()) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000326 // if C is zero, then both A and B qualify as mask
Sanjay Patel77bf6222017-04-03 16:53:12 +0000327 MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
328 : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
329 if (IsAPow2)
330 MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
331 : (AMask_AllOnes | AMask_Mixed));
332 if (IsBPow2)
333 MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
334 : (BMask_AllOnes | BMask_Mixed));
335 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000336 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000337
Owen Anderson3fe002d2010-09-08 22:16:17 +0000338 if (A == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000339 MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
340 : (AMask_NotAllOnes | AMask_NotMixed));
341 if (IsAPow2)
342 MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
343 : (Mask_AllZeros | AMask_Mixed));
344 } else if (ACst && CCst && ConstantExpr::getAnd(ACst, CCst) == CCst) {
345 MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000346 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000347
Craig Topperae48cb22012-12-20 07:15:54 +0000348 if (B == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000349 MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
350 : (BMask_NotAllOnes | BMask_NotMixed));
351 if (IsBPow2)
352 MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
353 : (Mask_AllZeros | BMask_Mixed));
354 } else if (BCst && CCst && ConstantExpr::getAnd(BCst, CCst) == CCst) {
355 MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000356 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000357
358 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000359}
360
Tim Northoverc0756c42013-09-04 11:57:13 +0000361/// Convert an analysis of a masked ICmp into its equivalent if all boolean
362/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
363/// is adjacent to the corresponding normal flag (recording ==), this just
364/// involves swapping those bits over.
365static unsigned conjugateICmpMask(unsigned Mask) {
366 unsigned NewMask;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000367 NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
368 AMask_Mixed | BMask_Mixed))
Tim Northoverc0756c42013-09-04 11:57:13 +0000369 << 1;
370
Sanjay Patel77bf6222017-04-03 16:53:12 +0000371 NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
372 AMask_NotMixed | BMask_NotMixed))
373 >> 1;
Tim Northoverc0756c42013-09-04 11:57:13 +0000374
375 return NewMask;
376}
377
Sanjay Patel77bf6222017-04-03 16:53:12 +0000378/// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
379/// Return the set of pattern classes (from MaskedICmpType) that both LHS and
380/// RHS satisfy.
381static unsigned getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C,
382 Value *&D, Value *&E, ICmpInst *LHS,
383 ICmpInst *RHS,
384 ICmpInst::Predicate &PredL,
385 ICmpInst::Predicate &PredR) {
386 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
387 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000388 // vectors are not (yet?) supported
Sanjay Patel77bf6222017-04-03 16:53:12 +0000389 if (LHS->getOperand(0)->getType()->isVectorTy())
390 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000391
392 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000393 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000394 // and L11 & L12 == L21 & L22. The same goes for RHS.
395 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000396 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000397 // above.
398 Value *L1 = LHS->getOperand(0);
399 Value *L2 = LHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000400 Value *L11, *L12, *L21, *L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000401 // Check whether the icmp can be decomposed into a bit test.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000402 if (decomposeBitTestICmp(LHS, PredL, L11, L12, L2)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000403 L21 = L22 = L1 = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000404 } else {
405 // Look for ANDs in the LHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000406 if (!L1->getType()->isIntegerTy()) {
407 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000408 L11 = L12 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000409 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
410 // Any icmp can be viewed as being trivially masked; if it allows us to
411 // remove one, it's worth it.
412 L11 = L1;
413 L12 = Constant::getAllOnesValue(L1->getType());
414 }
415
416 if (!L2->getType()->isIntegerTy()) {
417 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000418 L21 = L22 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000419 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
420 L21 = L2;
421 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000422 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000423 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000424
425 // Bail if LHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000426 if (!ICmpInst::isEquality(PredL))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000427 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000428
429 Value *R1 = RHS->getOperand(0);
430 Value *R2 = RHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000431 Value *R11, *R12;
432 bool Ok = false;
433 if (decomposeBitTestICmp(RHS, PredR, R11, R12, R2)) {
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000434 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000435 A = R11;
436 D = R12;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000437 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000438 A = R12;
439 D = R11;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000440 } else {
441 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000442 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000443 E = R2;
444 R1 = nullptr;
445 Ok = true;
Tim Northoverdc647a22013-09-04 11:57:17 +0000446 } else if (R1->getType()->isIntegerTy()) {
447 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
448 // As before, model no mask as a trivial mask if it'll let us do an
Mayur Pandey75b76c62014-08-19 06:41:55 +0000449 // optimization.
Tim Northoverdc647a22013-09-04 11:57:17 +0000450 R11 = R1;
451 R12 = Constant::getAllOnesValue(R1->getType());
452 }
453
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000454 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000455 A = R11;
456 D = R12;
457 E = R2;
458 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000459 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000460 A = R12;
461 D = R11;
462 E = R2;
463 Ok = true;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000464 }
465 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000466
467 // Bail if RHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000468 if (!ICmpInst::isEquality(PredR))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000469 return 0;
470
Chad Rosier58919cc2016-05-09 21:37:43 +0000471 // Look for ANDs on the right side of the RHS icmp.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000472 if (!Ok && R2->getType()->isIntegerTy()) {
Tim Northoverdc647a22013-09-04 11:57:17 +0000473 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
474 R11 = R2;
475 R12 = Constant::getAllOnesValue(R2->getType());
476 }
477
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000478 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000479 A = R11;
480 D = R12;
481 E = R1;
482 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000483 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000484 A = R12;
485 D = R11;
486 E = R1;
487 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000488 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000489 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000490 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000491 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000492 if (!Ok)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000493 return 0;
494
495 if (L11 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000496 B = L12;
497 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000498 } else if (L12 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000499 B = L11;
500 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000501 } else if (L21 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000502 B = L22;
503 C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000504 } else if (L22 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000505 B = L21;
506 C = L1;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000507 }
508
Sanjay Patel77bf6222017-04-03 16:53:12 +0000509 unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
510 unsigned RightType = getMaskedICmpType(A, D, E, PredR);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000511 return LeftType & RightType;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000512}
Sanjay Patel18549272015-09-08 18:24:36 +0000513
514/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
515/// into a single (icmp(A & X) ==/!= Y).
David Majnemer1a3327b2014-11-18 09:31:36 +0000516static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
517 llvm::InstCombiner::BuilderTy *Builder) {
Craig Topperf40110f2014-04-25 05:29:35 +0000518 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000519 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
520 unsigned Mask =
521 getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
522 if (Mask == 0)
523 return nullptr;
524
525 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
526 "Expected equality predicates for masked type of icmps.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000527
Tim Northoverc0756c42013-09-04 11:57:13 +0000528 // In full generality:
529 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
530 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
531 //
532 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
533 // equivalent to (icmp (A & X) !Op Y).
534 //
535 // Therefore, we can pretend for the rest of this function that we're dealing
536 // with the conjunction, provided we flip the sense of any comparisons (both
537 // input and output).
538
539 // In most cases we're going to produce an EQ for the "&&" case.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000540 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Tim Northoverc0756c42013-09-04 11:57:13 +0000541 if (!IsAnd) {
542 // Convert the masking analysis into its equivalent with negated
543 // comparisons.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000544 Mask = conjugateICmpMask(Mask);
Tim Northoverc0756c42013-09-04 11:57:13 +0000545 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000546
Sanjay Patel77bf6222017-04-03 16:53:12 +0000547 if (Mask & Mask_AllZeros) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000548 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000549 // -> (icmp eq (A & (B|D)), 0)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000550 Value *NewOr = Builder->CreateOr(B, D);
551 Value *NewAnd = Builder->CreateAnd(A, NewOr);
552 // We can't use C as zero because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000553 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000554 // with B and D, having a single bit set.
555 Value *Zero = Constant::getNullValue(A->getType());
556 return Builder->CreateICmp(NewCC, NewAnd, Zero);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000557 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000558 if (Mask & BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000559 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000560 // -> (icmp eq (A & (B|D)), (B|D))
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000561 Value *NewOr = Builder->CreateOr(B, D);
562 Value *NewAnd = Builder->CreateAnd(A, NewOr);
563 return Builder->CreateICmp(NewCC, NewAnd, NewOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000564 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000565 if (Mask & AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000566 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000567 // -> (icmp eq (A & (B&D)), A)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000568 Value *NewAnd1 = Builder->CreateAnd(B, D);
569 Value *NewAnd2 = Builder->CreateAnd(A, NewAnd1);
570 return Builder->CreateICmp(NewCC, NewAnd2, A);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000571 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000572
573 // Remaining cases assume at least that B and D are constant, and depend on
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000574 // their actual values. This isn't strictly necessary, just a "handle the
Tim Northoverc0756c42013-09-04 11:57:13 +0000575 // easy cases for now" decision.
576 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000577 if (!BCst)
578 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000579 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000580 if (!DCst)
581 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000582
Sanjay Patel77bf6222017-04-03 16:53:12 +0000583 if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000584 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
585 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
586 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
587 // Only valid if one of the masks is a superset of the other (check "B&D" is
588 // the same as either B or D).
589 APInt NewMask = BCst->getValue() & DCst->getValue();
590
591 if (NewMask == BCst->getValue())
592 return LHS;
593 else if (NewMask == DCst->getValue())
594 return RHS;
595 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000596
597 if (Mask & AMask_NotAllOnes) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000598 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
599 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
600 // Only valid if one of the masks is a superset of the other (check "B|D" is
601 // the same as either B or D).
602 APInt NewMask = BCst->getValue() | DCst->getValue();
603
604 if (NewMask == BCst->getValue())
605 return LHS;
606 else if (NewMask == DCst->getValue())
607 return RHS;
608 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000609
610 if (Mask & BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000611 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000612 // We already know that B & C == C && D & E == E.
613 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
614 // C and E, which are shared by both the mask B and the mask D, don't
615 // contradict, then we can transform to
616 // -> (icmp eq (A & (B|D)), (C|E))
617 // Currently, we only handle the case of B, C, D, and E being constant.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000618 // We can't simply use C and E because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000619 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000620 // with B and D, having a single bit set.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000621 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000622 if (!CCst)
623 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000624 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000625 if (!ECst)
626 return nullptr;
627 if (PredL != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000628 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000629 if (PredR != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000630 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000631
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000632 // If there is a conflict, we should actually return a false for the
633 // whole construct.
David Majnemer1a3327b2014-11-18 09:31:36 +0000634 if (((BCst->getValue() & DCst->getValue()) &
Craig Topper73ba1c82017-06-07 07:40:37 +0000635 (CCst->getValue() ^ ECst->getValue())).getBoolValue())
David Majnemer6fdb6b82014-11-18 09:31:41 +0000636 return ConstantInt::get(LHS->getType(), !IsAnd);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000637
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000638 Value *NewOr1 = Builder->CreateOr(B, D);
639 Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
640 Value *NewAnd = Builder->CreateAnd(A, NewOr1);
641 return Builder->CreateICmp(NewCC, NewAnd, NewOr2);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000642 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000643
Craig Topperf40110f2014-04-25 05:29:35 +0000644 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000645}
646
Erik Ecksteind1817522014-12-03 10:39:15 +0000647/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
648/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
649/// If \p Inverted is true then the check is for the inverted range, e.g.
650/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
651Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
652 bool Inverted) {
653 // Check the lower range comparison, e.g. x >= 0
654 // InstCombine already ensured that if there is a constant it's on the RHS.
655 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
656 if (!RangeStart)
657 return nullptr;
658
659 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
660 Cmp0->getPredicate());
661
662 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
663 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
664 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
665 return nullptr;
666
667 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
668 Cmp1->getPredicate());
669
670 Value *Input = Cmp0->getOperand(0);
671 Value *RangeEnd;
672 if (Cmp1->getOperand(0) == Input) {
673 // For the upper range compare we have: icmp x, n
674 RangeEnd = Cmp1->getOperand(1);
675 } else if (Cmp1->getOperand(1) == Input) {
676 // For the upper range compare we have: icmp n, x
677 RangeEnd = Cmp1->getOperand(0);
678 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
679 } else {
680 return nullptr;
681 }
682
683 // Check the upper range comparison, e.g. x < n
684 ICmpInst::Predicate NewPred;
685 switch (Pred1) {
686 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
687 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
688 default: return nullptr;
689 }
690
691 // This simplification is only valid if the upper range is not negative.
Craig Topper1a36b7d2017-05-15 06:39:41 +0000692 KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
693 if (!Known.isNonNegative())
Erik Ecksteind1817522014-12-03 10:39:15 +0000694 return nullptr;
695
696 if (Inverted)
697 NewPred = ICmpInst::getInversePredicate(NewPred);
698
699 return Builder->CreateICmp(NewPred, Input, RangeEnd);
700}
701
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000702static Value *
703foldAndOrOfEqualityCmpsWithConstants(ICmpInst *LHS, ICmpInst *RHS,
704 bool JoinedByAnd,
705 InstCombiner::BuilderTy *Builder) {
Sanjay Patelef9f5862017-04-15 17:55:06 +0000706 Value *X = LHS->getOperand(0);
707 if (X != RHS->getOperand(0))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000708 return nullptr;
709
Sanjay Patelef9f5862017-04-15 17:55:06 +0000710 const APInt *C1, *C2;
711 if (!match(LHS->getOperand(1), m_APInt(C1)) ||
712 !match(RHS->getOperand(1), m_APInt(C2)))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000713 return nullptr;
714
715 // We only handle (X != C1 && X != C2) and (X == C1 || X == C2).
716 ICmpInst::Predicate Pred = LHS->getPredicate();
717 if (Pred != RHS->getPredicate())
718 return nullptr;
719 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
720 return nullptr;
721 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
722 return nullptr;
723
724 // The larger unsigned constant goes on the right.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000725 if (C1->ugt(*C2))
726 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000727
Sanjay Patelef9f5862017-04-15 17:55:06 +0000728 APInt Xor = *C1 ^ *C2;
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000729 if (Xor.isPowerOf2()) {
730 // If LHSC and RHSC differ by only one bit, then set that bit in X and
731 // compare against the larger constant:
732 // (X == C1 || X == C2) --> (X | (C1 ^ C2)) == C2
733 // (X != C1 && X != C2) --> (X | (C1 ^ C2)) != C2
734 // We choose an 'or' with a Pow2 constant rather than the inverse mask with
735 // 'and' because that may lead to smaller codegen from a smaller constant.
736 Value *Or = Builder->CreateOr(X, ConstantInt::get(X->getType(), Xor));
Sanjay Patelef9f5862017-04-15 17:55:06 +0000737 return Builder->CreateICmp(Pred, Or, ConstantInt::get(X->getType(), *C2));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000738 }
739
740 // Special case: get the ordering right when the values wrap around zero.
741 // Ie, we assumed the constants were unsigned when swapping earlier.
Craig Topper73ba1c82017-06-07 07:40:37 +0000742 if (C1->isNullValue() && C2->isAllOnesValue())
Sanjay Patelef9f5862017-04-15 17:55:06 +0000743 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000744
Sanjay Patelef9f5862017-04-15 17:55:06 +0000745 if (*C1 == *C2 - 1) {
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000746 // (X == 13 || X == 14) --> X - 13 <=u 1
747 // (X != 13 && X != 14) --> X - 13 >u 1
748 // An 'add' is the canonical IR form, so favor that over a 'sub'.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000749 Value *Add = Builder->CreateAdd(X, ConstantInt::get(X->getType(), -(*C1)));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000750 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
751 return Builder->CreateICmp(NewPred, Add, ConstantInt::get(X->getType(), 1));
752 }
753
754 return nullptr;
755}
756
Craig Topperda6ea0d2017-06-16 05:10:37 +0000757// Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
758// Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
759Value *InstCombiner::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS,
760 bool JoinedByAnd,
761 Instruction &CxtI) {
762 ICmpInst::Predicate Pred = LHS->getPredicate();
763 if (Pred != RHS->getPredicate())
764 return nullptr;
765 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
766 return nullptr;
767 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
768 return nullptr;
769
770 // TODO support vector splats
771 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
772 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
773 if (!LHSC || !RHSC || !LHSC->isZero() || !RHSC->isZero())
774 return nullptr;
775
776 Value *A, *B, *C, *D;
777 if (match(LHS->getOperand(0), m_And(m_Value(A), m_Value(B))) &&
778 match(RHS->getOperand(0), m_And(m_Value(C), m_Value(D)))) {
779 if (A == D || B == D)
780 std::swap(C, D);
781 if (B == C)
782 std::swap(A, B);
783
784 if (A == C &&
785 isKnownToBeAPowerOfTwo(B, false, 0, &CxtI) &&
786 isKnownToBeAPowerOfTwo(D, false, 0, &CxtI)) {
787 Value *Mask = Builder->CreateOr(B, D);
788 Value *Masked = Builder->CreateAnd(A, Mask);
789 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
790 return Builder->CreateICmp(NewPred, Masked, Mask);
791 }
792 }
793
794 return nullptr;
795}
796
Sanjay Patel18549272015-09-08 18:24:36 +0000797/// Fold (icmp)&(icmp) if possible.
Craig Topperda6ea0d2017-06-16 05:10:37 +0000798Value *InstCombiner::foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS,
799 Instruction &CxtI) {
800 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
801 // if K1 and K2 are a one-bit mask.
802 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, true, CxtI))
803 return V;
804
Sanjay Patel519a87a2017-04-05 17:38:34 +0000805 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000806
807 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000808 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000809 if (LHS->getOperand(0) == RHS->getOperand(1) &&
810 LHS->getOperand(1) == RHS->getOperand(0))
811 LHS->swapOperands();
812 if (LHS->getOperand(0) == RHS->getOperand(0) &&
813 LHS->getOperand(1) == RHS->getOperand(1)) {
814 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
815 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
816 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000817 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000818 }
819 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000820
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000821 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000822 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000823 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000824
Erik Ecksteind1817522014-12-03 10:39:15 +0000825 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
826 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
827 return V;
828
829 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
830 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
831 return V;
832
Sanjay Patelef9f5862017-04-15 17:55:06 +0000833 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, true, Builder))
834 return V;
835
Chris Lattner0a8191e2010-01-05 07:50:36 +0000836 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Sanjay Patele4159d22017-04-10 19:38:36 +0000837 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000838 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
839 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
840 if (!LHSC || !RHSC)
841 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000842
Sanjay Patel519a87a2017-04-05 17:38:34 +0000843 if (LHSC == RHSC && PredL == PredR) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000844 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000845 // where C is a power of 2 or
Chris Lattner0a8191e2010-01-05 07:50:36 +0000846 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000847 if ((PredL == ICmpInst::ICMP_ULT && LHSC->getValue().isPowerOf2()) ||
848 (PredL == ICmpInst::ICMP_EQ && LHSC->isZero())) {
Sanjay Patele4159d22017-04-10 19:38:36 +0000849 Value *NewOr = Builder->CreateOr(LHS0, RHS0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000850 return Builder->CreateICmp(PredL, NewOr, LHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000851 }
852 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000853
Benjamin Kramer101720f2011-04-28 20:09:57 +0000854 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000855 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000856 // iff the lower bits of C2 and CA are zero.
Sanjay Patel519a87a2017-04-05 17:38:34 +0000857 if (PredL == ICmpInst::ICMP_EQ && PredL == PredR && LHS->hasOneUse() &&
858 RHS->hasOneUse()) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000859 Value *V;
Sanjay Patel519a87a2017-04-05 17:38:34 +0000860 ConstantInt *AndC, *SmallC = nullptr, *BigC = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000861
862 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000863 // (and x, CA) == C2 & (trunc x) == C1
Sanjay Patele4159d22017-04-10 19:38:36 +0000864 if (match(RHS0, m_Trunc(m_Value(V))) &&
865 match(LHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000866 SmallC = RHSC;
867 BigC = LHSC;
Sanjay Patele4159d22017-04-10 19:38:36 +0000868 } else if (match(LHS0, m_Trunc(m_Value(V))) &&
869 match(RHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000870 SmallC = LHSC;
871 BigC = RHSC;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000872 }
873
Sanjay Patel519a87a2017-04-05 17:38:34 +0000874 if (SmallC && BigC) {
875 unsigned BigBitSize = BigC->getType()->getBitWidth();
876 unsigned SmallBitSize = SmallC->getType()->getBitWidth();
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000877
878 // Check that the low bits are zero.
879 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Craig Topper73ba1c82017-06-07 07:40:37 +0000880 if ((Low & AndC->getValue()).isNullValue() &&
881 (Low & BigC->getValue()).isNullValue()) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000882 Value *NewAnd = Builder->CreateAnd(V, Low | AndC->getValue());
883 APInt N = SmallC->getValue().zext(BigBitSize) | BigC->getValue();
884 Value *NewVal = ConstantInt::get(AndC->getType()->getContext(), N);
885 return Builder->CreateICmp(PredL, NewAnd, NewVal);
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000886 }
887 }
888 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000889
Chris Lattner0a8191e2010-01-05 07:50:36 +0000890 // From here on, we only handle:
891 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +0000892 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000893 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000894
Sanjay Patel519a87a2017-04-05 17:38:34 +0000895 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
896 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
897 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
898 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
899 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000900 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000901
Chris Lattner0a8191e2010-01-05 07:50:36 +0000902 // We can't fold (ugt x, C) & (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +0000903 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +0000904 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000905
Chris Lattner0a8191e2010-01-05 07:50:36 +0000906 // Ensure that the larger constant is on the RHS.
907 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +0000908 if (CmpInst::isSigned(PredL) ||
909 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +0000910 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +0000911 else
912 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000913
Chris Lattner0a8191e2010-01-05 07:50:36 +0000914 if (ShouldSwap) {
915 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000916 std::swap(LHSC, RHSC);
917 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000918 }
919
Dan Gohman4a618822010-02-10 16:03:48 +0000920 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000921 // comparing a value against two constants and and'ing the result
922 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +0000923 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
924 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +0000925 // are not equal and that the larger constant is on the RHS
Sanjay Patel519a87a2017-04-05 17:38:34 +0000926 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000927
Sanjay Patel519a87a2017-04-05 17:38:34 +0000928 switch (PredL) {
929 default:
930 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000931 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000932 switch (PredR) {
933 default:
934 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000935 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000936 if (LHSC == SubOne(RHSC)) // (X != 13 & X u< 14) -> X < 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000937 return Builder->CreateICmpULT(LHS0, LHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000938 if (LHSC->isNullValue()) // (X != 0 & X u< 14) -> X-1 u< 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000939 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
Sanjay Patel85d79742016-08-31 19:49:56 +0000940 false, true);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000941 break; // (X != 13 & X u< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000942 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000943 if (LHSC == SubOne(RHSC)) // (X != 13 & X s< 14) -> X < 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000944 return Builder->CreateICmpSLT(LHS0, LHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000945 break; // (X != 13 & X s< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000946 case ICmpInst::ICMP_NE:
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000947 // Potential folds for this case should already be handled.
948 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000949 }
950 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000951 case ICmpInst::ICMP_UGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000952 switch (PredR) {
953 default:
954 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000955 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000956 if (RHSC == AddOne(LHSC)) // (X u> 13 & X != 14) -> X u> 14
Sanjay Patele4159d22017-04-10 19:38:36 +0000957 return Builder->CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000958 break; // (X u> 13 & X != 15) -> no change
959 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000960 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
961 false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000962 }
963 break;
964 case ICmpInst::ICMP_SGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000965 switch (PredR) {
966 default:
967 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000968 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000969 if (RHSC == AddOne(LHSC)) // (X s> 13 & X != 14) -> X s> 14
Sanjay Patele4159d22017-04-10 19:38:36 +0000970 return Builder->CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000971 break; // (X s> 13 & X != 15) -> no change
972 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000973 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(), true,
Sanjay Patel519a87a2017-04-05 17:38:34 +0000974 true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000975 }
976 break;
977 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000978
Craig Topperf40110f2014-04-25 05:29:35 +0000979 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000980}
981
Sanjay Patel18549272015-09-08 18:24:36 +0000982/// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
983/// a Value which should already be inserted into the function.
Sanjay Patel5e456b92017-05-18 20:53:16 +0000984Value *InstCombiner::foldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +0000985 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
986 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
987 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
988
989 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
990 // Swap RHS operands to match LHS.
991 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
992 std::swap(Op1LHS, Op1RHS);
993 }
994
995 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
996 // Suppose the relation between x and y is R, where R is one of
997 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
998 // testing the desired relations.
999 //
1000 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1001 // bool(R & CC0) && bool(R & CC1)
1002 // = bool((R & CC0) & (R & CC1))
1003 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
1004 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1005 return getFCmpValue(getFCmpCode(Op0CC) & getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1006 Builder);
1007
Chris Lattner0a8191e2010-01-05 07:50:36 +00001008 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1009 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +00001010 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001011 return nullptr;
Benjamin Kramere89c7052013-04-12 21:56:23 +00001012
Chris Lattner0a8191e2010-01-05 07:50:36 +00001013 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1014 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1015 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1016 // If either of the constants are nans, then the whole thing returns
1017 // false.
1018 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001019 return Builder->getFalse();
Chris Lattner067459c2010-03-05 08:46:26 +00001020 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001021 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001022
Chris Lattner0a8191e2010-01-05 07:50:36 +00001023 // Handle vector zeros. This occurs because the canonical form of
1024 // "fcmp ord x,x" is "fcmp ord x, 0".
1025 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1026 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001027 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001028 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001029 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001030
Craig Topperf40110f2014-04-25 05:29:35 +00001031 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001032}
1033
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001034/// Match De Morgan's Laws:
1035/// (~A & ~B) == (~(A | B))
1036/// (~A | ~B) == (~(A & B))
1037static Instruction *matchDeMorgansLaws(BinaryOperator &I,
Sanjay Patel7caaa792017-05-09 20:05:05 +00001038 InstCombiner::BuilderTy &Builder) {
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001039 auto Opcode = I.getOpcode();
1040 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1041 "Trying to match De Morgan's Laws with something other than and/or");
1042
Sanjay Patel7caaa792017-05-09 20:05:05 +00001043 // Flip the logic operation.
1044 Opcode = (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
1045
1046 Value *A, *B;
1047 if (match(I.getOperand(0), m_OneUse(m_Not(m_Value(A)))) &&
1048 match(I.getOperand(1), m_OneUse(m_Not(m_Value(B)))) &&
1049 !IsFreeToInvert(A, A->hasOneUse()) &&
1050 !IsFreeToInvert(B, B->hasOneUse())) {
1051 Value *AndOr = Builder.CreateBinOp(Opcode, A, B, I.getName() + ".demorgan");
1052 return BinaryOperator::CreateNot(AndOr);
1053 }
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001054
1055 return nullptr;
1056}
1057
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001058bool InstCombiner::shouldOptimizeCast(CastInst *CI) {
1059 Value *CastSrc = CI->getOperand(0);
1060
1061 // Noop casts and casts of constants should be eliminated trivially.
1062 if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
1063 return false;
1064
1065 // If this cast is paired with another cast that can be eliminated, we prefer
1066 // to have it eliminated.
1067 if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
1068 if (isEliminableCastPair(PrecedingCI, CI))
1069 return false;
1070
1071 // If this is a vector sext from a compare, then we don't want to break the
1072 // idiom where each element of the extended vector is either zero or all ones.
1073 if (CI->getOpcode() == Instruction::SExt &&
1074 isa<CmpInst>(CastSrc) && CI->getDestTy()->isVectorTy())
1075 return false;
1076
1077 return true;
1078}
1079
Sanjay Patel60312bc42016-09-12 00:16:23 +00001080/// Fold {and,or,xor} (cast X), C.
1081static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
1082 InstCombiner::BuilderTy *Builder) {
1083 Constant *C;
1084 if (!match(Logic.getOperand(1), m_Constant(C)))
1085 return nullptr;
1086
1087 auto LogicOpc = Logic.getOpcode();
1088 Type *DestTy = Logic.getType();
1089 Type *SrcTy = Cast->getSrcTy();
1090
Sanjay Pateld1e81192017-06-22 15:46:54 +00001091 // Move the logic operation ahead of a zext if the constant is unchanged in
1092 // the smaller source type. Performing the logic in a smaller type may provide
1093 // more information to later folds, and the smaller logic instruction may be
1094 // cheaper (particularly in the case of vectors).
Sanjay Patel60312bc42016-09-12 00:16:23 +00001095 Value *X;
Sanjay Patel60312bc42016-09-12 00:16:23 +00001096 if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1097 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1098 Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1099 if (ZextTruncC == C) {
1100 // LogicOpc (zext X), C --> zext (LogicOpc X, C)
1101 Value *NewOp = Builder->CreateBinOp(LogicOpc, X, TruncC);
1102 return new ZExtInst(NewOp, DestTy);
1103 }
1104 }
1105
1106 return nullptr;
1107}
1108
1109/// Fold {and,or,xor} (cast X), Y.
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001110Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001111 auto LogicOpc = I.getOpcode();
Sanjay Patel1e6ca442016-11-22 22:54:36 +00001112 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001113
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001114 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001115 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
Sanjay Patel9bba7502016-03-03 19:19:04 +00001116 if (!Cast0)
Sanjay Patel7d0d8102016-02-23 16:59:21 +00001117 return nullptr;
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001118
Sanjay Patel9bba7502016-03-03 19:19:04 +00001119 // This must be a cast from an integer or integer vector source type to allow
1120 // transformation of the logic operation to the source type.
1121 Type *DestTy = I.getType();
Sanjay Patel713f25e2016-02-23 17:41:34 +00001122 Type *SrcTy = Cast0->getSrcTy();
Sanjay Patel9bba7502016-03-03 19:19:04 +00001123 if (!SrcTy->isIntOrIntVectorTy())
1124 return nullptr;
1125
Sanjay Patel60312bc42016-09-12 00:16:23 +00001126 if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1127 return Ret;
Sanjay Patel0753c062016-07-21 00:24:18 +00001128
Sanjay Patel9bba7502016-03-03 19:19:04 +00001129 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1130 if (!Cast1)
1131 return nullptr;
1132
1133 // Both operands of the logic operation are casts. The casts must be of the
1134 // same type for reduction.
1135 auto CastOpcode = Cast0->getOpcode();
1136 if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
Sanjay Patel713f25e2016-02-23 17:41:34 +00001137 return nullptr;
1138
1139 Value *Cast0Src = Cast0->getOperand(0);
1140 Value *Cast1Src = Cast1->getOperand(0);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001141
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001142 // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
Tobias Grosser8757e382016-08-03 19:30:35 +00001143 if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001144 Value *NewOp = Builder->CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
1145 I.getName());
Sanjay Patel713f25e2016-02-23 17:41:34 +00001146 return CastInst::Create(CastOpcode, NewOp, DestTy);
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001147 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001148
Sanjay Pateldbbaca02016-02-24 17:00:34 +00001149 // For now, only 'and'/'or' have optimizations after this.
1150 if (LogicOpc == Instruction::Xor)
1151 return nullptr;
1152
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001153 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001154 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001155 ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1156 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1157 if (ICmp0 && ICmp1) {
Craig Topperda6ea0d2017-06-16 05:10:37 +00001158 Value *Res = LogicOpc == Instruction::And ? foldAndOfICmps(ICmp0, ICmp1, I)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001159 : foldOrOfICmps(ICmp0, ICmp1, I);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001160 if (Res)
1161 return CastInst::Create(CastOpcode, Res, DestTy);
1162 return nullptr;
1163 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001164
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001165 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001166 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001167 FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1168 FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1169 if (FCmp0 && FCmp1) {
Sanjay Patel5e456b92017-05-18 20:53:16 +00001170 Value *Res = LogicOpc == Instruction::And ? foldAndOfFCmps(FCmp0, FCmp1)
1171 : foldOrOfFCmps(FCmp0, FCmp1);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001172 if (Res)
1173 return CastInst::Create(CastOpcode, Res, DestTy);
1174 return nullptr;
1175 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001176
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001177 return nullptr;
1178}
1179
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001180static Instruction *foldBoolSextMaskToSelect(BinaryOperator &I) {
1181 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1182
1183 // Canonicalize SExt or Not to the LHS
1184 if (match(Op1, m_SExt(m_Value())) || match(Op1, m_Not(m_Value()))) {
1185 std::swap(Op0, Op1);
1186 }
1187
1188 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1189 Value *X = nullptr;
1190 if (match(Op0, m_SExt(m_Value(X))) &&
1191 X->getType()->getScalarType()->isIntegerTy(1)) {
1192 Value *Zero = Constant::getNullValue(Op1->getType());
1193 return SelectInst::Create(X, Op1, Zero);
1194 }
1195
1196 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1197 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1198 X->getType()->getScalarType()->isIntegerTy(1)) {
1199 Value *Zero = Constant::getNullValue(Op0->getType());
1200 return SelectInst::Create(X, Zero, Op1);
1201 }
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001202
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001203 return nullptr;
1204}
1205
Sanjay Patele0c26e02017-04-23 22:00:02 +00001206static Instruction *foldAndToXor(BinaryOperator &I,
1207 InstCombiner::BuilderTy &Builder) {
1208 assert(I.getOpcode() == Instruction::And);
1209 Value *Op0 = I.getOperand(0);
1210 Value *Op1 = I.getOperand(1);
1211 Value *A, *B;
1212
1213 // Operand complexity canonicalization guarantees that the 'or' is Op0.
1214 // (A | B) & ~(A & B) --> A ^ B
1215 // (A | B) & ~(B & A) --> A ^ B
1216 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1217 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B)))))
1218 return BinaryOperator::CreateXor(A, B);
1219
1220 // (A | ~B) & (~A | B) --> ~(A ^ B)
1221 // (A | ~B) & (B | ~A) --> ~(A ^ B)
1222 // (~B | A) & (~A | B) --> ~(A ^ B)
1223 // (~B | A) & (B | ~A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001224 if (Op0->hasOneUse() || Op1->hasOneUse())
1225 if (match(Op0, m_c_Or(m_Value(A), m_Not(m_Value(B)))) &&
1226 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B))))
1227 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001228
1229 return nullptr;
1230}
1231
1232static Instruction *foldOrToXor(BinaryOperator &I,
1233 InstCombiner::BuilderTy &Builder) {
1234 assert(I.getOpcode() == Instruction::Or);
1235 Value *Op0 = I.getOperand(0);
1236 Value *Op1 = I.getOperand(1);
1237 Value *A, *B;
1238
1239 // Operand complexity canonicalization guarantees that the 'and' is Op0.
1240 // (A & B) | ~(A | B) --> ~(A ^ B)
1241 // (A & B) | ~(B | A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001242 if (Op0->hasOneUse() || Op1->hasOneUse())
1243 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1244 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1245 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001246
1247 // (A & ~B) | (~A & B) --> A ^ B
1248 // (A & ~B) | (B & ~A) --> A ^ B
1249 // (~B & A) | (~A & B) --> A ^ B
1250 // (~B & A) | (B & ~A) --> A ^ B
1251 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
1252 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
1253 return BinaryOperator::CreateXor(A, B);
1254
1255 return nullptr;
1256}
1257
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001258// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1259// here. We should standardize that construct where it is needed or choose some
1260// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001261Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001262 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001263 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1264
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001265 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001266 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001267
Craig Toppera4205622017-06-09 03:21:29 +00001268 if (Value *V = SimplifyAndInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001269 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001270
Craig Topper9d4171a2012-12-20 07:09:41 +00001271 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001272 // purpose is to compute bits we don't care about.
1273 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001274 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001275
Sanjay Patele0c26e02017-04-23 22:00:02 +00001276 // Do this before using distributive laws to catch simple and/or/not patterns.
1277 if (Instruction *Xor = foldAndToXor(I, *Builder))
1278 return Xor;
1279
1280 // (A|B)&(A|C) -> A|(B&C) etc
1281 if (Value *V = SimplifyUsingDistributiveLaws(I))
1282 return replaceInstUsesWith(I, V);
1283
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001284 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001285 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001286
Chris Lattner0a8191e2010-01-05 07:50:36 +00001287 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1288 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001289
1290 // Optimize a variety of ((val OP C1) & C2) combinations...
1291 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1292 Value *Op0LHS = Op0I->getOperand(0);
1293 Value *Op0RHS = Op0I->getOperand(1);
1294 switch (Op0I->getOpcode()) {
1295 default: break;
1296 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001297 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001298 // If the mask is only needed on one incoming arm, push it up.
1299 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001300
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001301 APInt NotAndRHS(~AndRHSMask);
Hal Finkel60db0582014-09-07 18:57:58 +00001302 if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001303 // Not masking anything out for the LHS, move to RHS.
1304 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1305 Op0RHS->getName()+".masked");
1306 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1307 }
1308 if (!isa<Constant>(Op0RHS) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001309 MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001310 // Not masking anything out for the RHS, move to LHS.
1311 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1312 Op0LHS->getName()+".masked");
1313 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1314 }
1315
1316 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001317 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001318 case Instruction::Sub:
Balaram Makamccf59732015-08-20 15:35:00 +00001319 // -x & 1 -> x & 1
Craig Topper73ba1c82017-06-07 07:40:37 +00001320 if (AndRHSMask.isOneValue() && match(Op0LHS, m_Zero()))
Balaram Makamccf59732015-08-20 15:35:00 +00001321 return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
1322
Chris Lattner0a8191e2010-01-05 07:50:36 +00001323 break;
1324
1325 case Instruction::Shl:
1326 case Instruction::LShr:
1327 // (1 << x) & 1 --> zext(x == 0)
1328 // (1 >> x) & 1 --> zext(x == 0)
Craig Topper73ba1c82017-06-07 07:40:37 +00001329 if (AndRHSMask.isOneValue() && Op0LHS == AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001330 Value *NewICmp =
1331 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1332 return new ZExtInst(NewICmp, I.getType());
1333 }
1334 break;
1335 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001336
David Majnemerde55c602017-01-17 18:08:06 +00001337 // ((C1 OP zext(X)) & C2) -> zext((C1-X) & C2) if C2 fits in the bitwidth
1338 // of X and OP behaves well when given trunc(C1) and X.
1339 switch (Op0I->getOpcode()) {
1340 default:
1341 break;
1342 case Instruction::Xor:
1343 case Instruction::Or:
1344 case Instruction::Mul:
1345 case Instruction::Add:
1346 case Instruction::Sub:
1347 Value *X;
1348 ConstantInt *C1;
Craig Topperb5194ee2017-04-12 05:49:28 +00001349 if (match(Op0I, m_c_BinOp(m_ZExt(m_Value(X)), m_ConstantInt(C1)))) {
David Majnemerde55c602017-01-17 18:08:06 +00001350 if (AndRHSMask.isIntN(X->getType()->getScalarSizeInBits())) {
1351 auto *TruncC1 = ConstantExpr::getTrunc(C1, X->getType());
1352 Value *BinOp;
1353 if (isa<ZExtInst>(Op0LHS))
1354 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), X, TruncC1);
1355 else
1356 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), TruncC1, X);
1357 auto *TruncC2 = ConstantExpr::getTrunc(AndRHS, X->getType());
1358 auto *And = Builder->CreateAnd(BinOp, TruncC2);
1359 return new ZExtInst(And, I.getType());
1360 }
1361 }
1362 }
1363
Chris Lattner0a8191e2010-01-05 07:50:36 +00001364 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1365 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1366 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001367 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001368
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001369 // If this is an integer truncation, and if the source is an 'and' with
1370 // immediate, transform it. This frequently occurs for bitfield accesses.
1371 {
Craig Topperf40110f2014-04-25 05:29:35 +00001372 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001373 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1374 // Change: and (trunc (and X, YC) to T), C2
1375 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001376 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001377 // other simplifications.
1378 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1379 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1380 C3 = ConstantExpr::getAnd(C3, AndRHS);
1381 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001382 }
1383 }
Craig Topper86173602017-04-04 20:26:25 +00001384 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001385
Craig Topper86173602017-04-04 20:26:25 +00001386 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001387 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1388 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001389
Sanjay Patel7caaa792017-05-09 20:05:05 +00001390 if (Instruction *DeMorgan = matchDeMorgansLaws(I, *Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001391 return DeMorgan;
Craig Topper9d4171a2012-12-20 07:09:41 +00001392
Chris Lattner0a8191e2010-01-05 07:50:36 +00001393 {
Sanjay Patele0c26e02017-04-23 22:00:02 +00001394 Value *A = nullptr, *B = nullptr, *C = nullptr;
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001395 // A&(A^B) => A & ~B
1396 {
1397 Value *tmpOp0 = Op0;
1398 Value *tmpOp1 = Op1;
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001399 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001400 if (A == Op1 || B == Op1 ) {
1401 tmpOp1 = Op0;
1402 tmpOp0 = Op1;
1403 // Simplify below
1404 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001405 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001406
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001407 if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001408 if (B == tmpOp0) {
1409 std::swap(A, B);
1410 }
Sanjay Pateld09b44a2016-01-18 17:50:23 +00001411 // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001412 // A is originally -1 (or a vector of -1 and undefs), then we enter
1413 // an endless loop. By checking that A is non-constant we ensure that
1414 // we will never get to the loop.
1415 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001416 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001417 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001418 }
1419
1420 // (A&((~A)|B)) -> A&B
Craig Topperc4b48a32017-04-25 06:02:11 +00001421 if (match(Op0, m_c_Or(m_Not(m_Specific(Op1)), m_Value(A))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001422 return BinaryOperator::CreateAnd(A, Op1);
Craig Topperc4b48a32017-04-25 06:02:11 +00001423 if (match(Op1, m_c_Or(m_Not(m_Specific(Op0)), m_Value(A))))
Chris Lattner0a8191e2010-01-05 07:50:36 +00001424 return BinaryOperator::CreateAnd(A, Op0);
David Majnemer42af3602014-07-30 21:26:37 +00001425
1426 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1427 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1428 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001429 if (Op1->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
David Majnemer42af3602014-07-30 21:26:37 +00001430 return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1431
1432 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1433 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1434 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001435 if (Op0->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
David Majnemer42af3602014-07-30 21:26:37 +00001436 return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001437
1438 // (A | B) & ((~A) ^ B) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001439 // (A | B) & (B ^ (~A)) -> (A & B)
1440 // (B | A) & ((~A) ^ B) -> (A & B)
1441 // (B | A) & (B ^ (~A)) -> (A & B)
1442 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1443 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001444 return BinaryOperator::CreateAnd(A, B);
1445
1446 // ((~A) ^ B) & (A | B) -> (A & B)
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001447 // ((~A) ^ B) & (B | A) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001448 // (B ^ (~A)) & (A | B) -> (A & B)
1449 // (B ^ (~A)) & (B | A) -> (A & B)
1450 if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001451 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001452 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001453 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001454
David Majnemer5e96f1b2014-08-30 06:18:20 +00001455 {
1456 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1457 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1458 if (LHS && RHS)
Craig Topperda6ea0d2017-06-16 05:10:37 +00001459 if (Value *Res = foldAndOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001460 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001461
David Majnemer5e96f1b2014-08-30 06:18:20 +00001462 // TODO: Make this recursive; it's a little tricky because an arbitrary
1463 // number of 'and' instructions might have to be created.
1464 Value *X, *Y;
1465 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1466 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001467 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001468 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001469 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001470 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001471 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001472 }
1473 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1474 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001475 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001476 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001477 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001478 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001479 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001480 }
1481 }
1482
Chris Lattner4e8137d2010-02-11 06:26:33 +00001483 // If and'ing two fcmp, try combine them into one.
1484 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1485 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel5e456b92017-05-18 20:53:16 +00001486 if (Value *Res = foldAndOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001487 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001488
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001489 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1490 return CastedAnd;
Craig Topper9d4171a2012-12-20 07:09:41 +00001491
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001492 if (Instruction *Select = foldBoolSextMaskToSelect(I))
1493 return Select;
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001494
Craig Topperf40110f2014-04-25 05:29:35 +00001495 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001496}
1497
Chad Rosiera00df492016-05-25 16:22:14 +00001498/// Given an OR instruction, check to see if this is a bswap idiom. If so,
1499/// insert the new intrinsic and return it.
1500Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chad Rosiere5819e22016-05-26 14:58:51 +00001501 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1502
1503 // Look through zero extends.
1504 if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1505 Op0 = Ext->getOperand(0);
1506
1507 if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1508 Op1 = Ext->getOperand(0);
1509
1510 // (A | B) | C and A | (B | C) -> bswap if possible.
1511 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1512 match(Op1, m_Or(m_Value(), m_Value()));
1513
1514 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1515 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1516 match(Op1, m_LogicalShift(m_Value(), m_Value()));
1517
1518 // (A & B) | (C & D) -> bswap if possible.
1519 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1520 match(Op1, m_And(m_Value(), m_Value()));
1521
1522 if (!OrOfOrs && !OrOfShifts && !OrOfAnds)
1523 return nullptr;
1524
James Molloyf01488e2016-01-15 09:20:19 +00001525 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00001526 if (!recognizeBSwapOrBitReverseIdiom(&I, true, false, Insts))
Craig Topperf40110f2014-04-25 05:29:35 +00001527 return nullptr;
James Molloyf01488e2016-01-15 09:20:19 +00001528 Instruction *LastInst = Insts.pop_back_val();
1529 LastInst->removeFromParent();
Craig Topper9d4171a2012-12-20 07:09:41 +00001530
James Molloyf01488e2016-01-15 09:20:19 +00001531 for (auto *Inst : Insts)
1532 Worklist.Add(Inst);
1533 return LastInst;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001534}
1535
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001536/// If all elements of two constant vectors are 0/-1 and inverses, return true.
1537static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
1538 unsigned NumElts = C1->getType()->getVectorNumElements();
1539 for (unsigned i = 0; i != NumElts; ++i) {
1540 Constant *EltC1 = C1->getAggregateElement(i);
1541 Constant *EltC2 = C2->getAggregateElement(i);
1542 if (!EltC1 || !EltC2)
1543 return false;
1544
1545 // One element must be all ones, and the other must be all zeros.
1546 // FIXME: Allow undef elements.
1547 if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
1548 (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
1549 return false;
1550 }
1551 return true;
1552}
1553
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001554/// We have an expression of the form (A & C) | (B & D). If A is a scalar or
1555/// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
1556/// B, it can be used as the condition operand of a select instruction.
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001557static Value *getSelectCondition(Value *A, Value *B,
1558 InstCombiner::BuilderTy &Builder) {
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001559 // If these are scalars or vectors of i1, A can be used directly.
1560 Type *Ty = A->getType();
1561 if (match(A, m_Not(m_Specific(B))) && Ty->getScalarType()->isIntegerTy(1))
1562 return A;
1563
1564 // If A and B are sign-extended, look through the sexts to find the booleans.
1565 Value *Cond;
Sanjay Pateld1e81192017-06-22 15:46:54 +00001566 Value *NotB;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001567 if (match(A, m_SExt(m_Value(Cond))) &&
1568 Cond->getType()->getScalarType()->isIntegerTy(1) &&
Sanjay Pateld1e81192017-06-22 15:46:54 +00001569 match(B, m_OneUse(m_Not(m_Value(NotB))))) {
1570 NotB = peekThroughBitcast(NotB, true);
1571 if (match(NotB, m_SExt(m_Specific(Cond))))
1572 return Cond;
1573 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001574
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001575 // All scalar (and most vector) possibilities should be handled now.
1576 // Try more matches that only apply to non-splat constant vectors.
1577 if (!Ty->isVectorTy())
1578 return nullptr;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001579
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001580 // If both operands are constants, see if the constants are inverse bitmasks.
1581 Constant *AC, *BC;
1582 if (match(A, m_Constant(AC)) && match(B, m_Constant(BC)) &&
1583 areInverseVectorBitmasks(AC, BC))
1584 return ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1585
1586 // If both operands are xor'd with constants using the same sexted boolean
1587 // operand, see if the constants are inverse bitmasks.
1588 if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AC)))) &&
1589 match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BC)))) &&
1590 Cond->getType()->getScalarType()->isIntegerTy(1) &&
1591 areInverseVectorBitmasks(AC, BC)) {
1592 AC = ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1593 return Builder.CreateXor(Cond, AC);
1594 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001595 return nullptr;
1596}
1597
1598/// We have an expression of the form (A & C) | (B & D). Try to simplify this
1599/// to "A' ? C : D", where A' is a boolean or vector of booleans.
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001600static Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D,
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001601 InstCombiner::BuilderTy &Builder) {
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001602 // The potential condition of the select may be bitcasted. In that case, look
1603 // through its bitcast and the corresponding bitcast of the 'not' condition.
1604 Type *OrigType = A->getType();
Sanjay Patele800df8e2017-06-22 15:28:01 +00001605 A = peekThroughBitcast(A, true);
1606 B = peekThroughBitcast(B, true);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001607
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001608 if (Value *Cond = getSelectCondition(A, B, Builder)) {
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001609 // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001610 // The bitcasts will either all exist or all not exist. The builder will
1611 // not create unnecessary casts if the types already match.
1612 Value *BitcastC = Builder.CreateBitCast(C, A->getType());
1613 Value *BitcastD = Builder.CreateBitCast(D, A->getType());
1614 Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
1615 return Builder.CreateBitCast(Select, OrigType);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001616 }
Sanjay Patel5c0bc022016-06-02 18:03:05 +00001617
Craig Topperf40110f2014-04-25 05:29:35 +00001618 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001619}
1620
Sanjay Patel18549272015-09-08 18:24:36 +00001621/// Fold (icmp)|(icmp) if possible.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001622Value *InstCombiner::foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001623 Instruction &CxtI) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001624 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1625 // if K1 and K2 are a one-bit mask.
Craig Topperda6ea0d2017-06-16 05:10:37 +00001626 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, false, CxtI))
1627 return V;
1628
1629 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1630
Sanjay Patel519a87a2017-04-05 17:38:34 +00001631 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
1632 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001633
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001634 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1635 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1636 // The original condition actually refers to the following two ranges:
1637 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1638 // We can fold these two ranges if:
1639 // 1) C1 and C2 is unsigned greater than C3.
1640 // 2) The two ranges are separated.
1641 // 3) C1 ^ C2 is one-bit mask.
1642 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1643 // This implies all values in the two ranges differ by exactly one bit.
1644
Sanjay Patel519a87a2017-04-05 17:38:34 +00001645 if ((PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) &&
1646 PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() &&
1647 LHSC->getType() == RHSC->getType() &&
1648 LHSC->getValue() == (RHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001649
1650 Value *LAdd = LHS->getOperand(0);
1651 Value *RAdd = RHS->getOperand(0);
1652
1653 Value *LAddOpnd, *RAddOpnd;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001654 ConstantInt *LAddC, *RAddC;
1655 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddC))) &&
1656 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddC))) &&
1657 LAddC->getValue().ugt(LHSC->getValue()) &&
1658 RAddC->getValue().ugt(LHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001659
Sanjay Patel519a87a2017-04-05 17:38:34 +00001660 APInt DiffC = LAddC->getValue() ^ RAddC->getValue();
1661 if (LAddOpnd == RAddOpnd && DiffC.isPowerOf2()) {
1662 ConstantInt *MaxAddC = nullptr;
1663 if (LAddC->getValue().ult(RAddC->getValue()))
1664 MaxAddC = RAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001665 else
Sanjay Patel519a87a2017-04-05 17:38:34 +00001666 MaxAddC = LAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001667
Sanjay Patel519a87a2017-04-05 17:38:34 +00001668 APInt RRangeLow = -RAddC->getValue();
1669 APInt RRangeHigh = RRangeLow + LHSC->getValue();
1670 APInt LRangeLow = -LAddC->getValue();
1671 APInt LRangeHigh = LRangeLow + LHSC->getValue();
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001672 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1673 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1674 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1675 : RRangeLow - LRangeLow;
1676
1677 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
Sanjay Patel519a87a2017-04-05 17:38:34 +00001678 RangeDiff.ugt(LHSC->getValue())) {
1679 Value *MaskC = ConstantInt::get(LAddC->getType(), ~DiffC);
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001680
Sanjay Patel519a87a2017-04-05 17:38:34 +00001681 Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskC);
1682 Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddC);
1683 return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSC));
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001684 }
1685 }
1686 }
1687 }
1688
Chris Lattner0a8191e2010-01-05 07:50:36 +00001689 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001690 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001691 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1692 LHS->getOperand(1) == RHS->getOperand(0))
1693 LHS->swapOperands();
1694 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1695 LHS->getOperand(1) == RHS->getOperand(1)) {
1696 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1697 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1698 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001699 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001700 }
1701 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001702
1703 // handle (roughly):
1704 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001705 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001706 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001707
Sanjay Patele4159d22017-04-10 19:38:36 +00001708 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001709 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1710 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1711 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001712 Value *A = nullptr, *B = nullptr;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001713 if (PredL == ICmpInst::ICMP_EQ && LHSC && LHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001714 B = LHS0;
1715 if (PredR == ICmpInst::ICMP_ULT && LHS0 == RHS->getOperand(1))
1716 A = RHS0;
1717 else if (PredR == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001718 A = RHS->getOperand(1);
1719 }
1720 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1721 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001722 else if (PredR == ICmpInst::ICMP_EQ && RHSC && RHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001723 B = RHS0;
1724 if (PredL == ICmpInst::ICMP_ULT && RHS0 == LHS->getOperand(1))
1725 A = LHS0;
1726 else if (PredL == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001727 A = LHS->getOperand(1);
1728 }
1729 if (A && B)
1730 return Builder->CreateICmp(
1731 ICmpInst::ICMP_UGE,
1732 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1733 }
1734
Erik Ecksteind1817522014-12-03 10:39:15 +00001735 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1736 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1737 return V;
1738
1739 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1740 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1741 return V;
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001742
Sanjay Patelef9f5862017-04-15 17:55:06 +00001743 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, false, Builder))
1744 return V;
1745
David Majnemerc2a990b2013-07-05 00:31:17 +00001746 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001747 if (!LHSC || !RHSC)
1748 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001749
Sanjay Patel519a87a2017-04-05 17:38:34 +00001750 if (LHSC == RHSC && PredL == PredR) {
Owen Anderson8f306a72010-08-02 09:32:13 +00001751 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001752 if (PredL == ICmpInst::ICMP_NE && LHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001753 Value *NewOr = Builder->CreateOr(LHS0, RHS0);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001754 return Builder->CreateICmp(PredL, NewOr, LHSC);
Owen Anderson8f306a72010-08-02 09:32:13 +00001755 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001756 }
1757
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001758 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001759 // iff C2 + CA == C1.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001760 if (PredL == ICmpInst::ICMP_ULT && PredR == ICmpInst::ICMP_EQ) {
1761 ConstantInt *AddC;
Sanjay Patele4159d22017-04-10 19:38:36 +00001762 if (match(LHS0, m_Add(m_Specific(RHS0), m_ConstantInt(AddC))))
Sanjay Patel519a87a2017-04-05 17:38:34 +00001763 if (RHSC->getValue() + AddC->getValue() == LHSC->getValue())
Sanjay Patele4159d22017-04-10 19:38:36 +00001764 return Builder->CreateICmpULE(LHS0, LHSC);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001765 }
1766
Chris Lattner0a8191e2010-01-05 07:50:36 +00001767 // From here on, we only handle:
1768 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +00001769 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001770 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001771
Sanjay Patel519a87a2017-04-05 17:38:34 +00001772 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
1773 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
1774 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
1775 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
1776 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001777 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001778
Chris Lattner0a8191e2010-01-05 07:50:36 +00001779 // We can't fold (ugt x, C) | (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001780 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +00001781 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001782
Chris Lattner0a8191e2010-01-05 07:50:36 +00001783 // Ensure that the larger constant is on the RHS.
1784 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +00001785 if (CmpInst::isSigned(PredL) ||
1786 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +00001787 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +00001788 else
1789 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001790
Chris Lattner0a8191e2010-01-05 07:50:36 +00001791 if (ShouldSwap) {
1792 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001793 std::swap(LHSC, RHSC);
1794 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001795 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001796
Dan Gohman4a618822010-02-10 16:03:48 +00001797 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001798 // comparing a value against two constants and or'ing the result
1799 // together. Because of the above check, we know that we only have
1800 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1801 // icmp folding check above), that the two constants are not
1802 // equal.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001803 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001804
Sanjay Patel519a87a2017-04-05 17:38:34 +00001805 switch (PredL) {
1806 default:
1807 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001808 case ICmpInst::ICMP_EQ:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001809 switch (PredR) {
1810 default:
1811 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001812 case ICmpInst::ICMP_EQ:
Sanjay Patel7cfe4162017-04-14 19:23:50 +00001813 // Potential folds for this case should already be handled.
1814 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001815 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1816 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001817 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001818 }
1819 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001820 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001821 switch (PredR) {
1822 default:
1823 llvm_unreachable("Unknown integer condition code!");
1824 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001825 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001826 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001827 assert(!RHSC->isMaxValue(false) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001828 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1,
1829 false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001830 }
1831 break;
1832 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001833 switch (PredR) {
1834 default:
1835 llvm_unreachable("Unknown integer condition code!");
1836 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001837 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001838 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001839 assert(!RHSC->isMaxValue(true) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001840 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1, true,
Sanjay Patel519a87a2017-04-05 17:38:34 +00001841 false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001842 }
1843 break;
1844 }
Craig Topperf40110f2014-04-25 05:29:35 +00001845 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001846}
1847
Sanjay Patel18549272015-09-08 18:24:36 +00001848/// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
1849/// a Value which should already be inserted into the function.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001850Value *InstCombiner::foldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +00001851 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1852 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1853 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1854
1855 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1856 // Swap RHS operands to match LHS.
1857 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1858 std::swap(Op1LHS, Op1RHS);
1859 }
1860
1861 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1862 // This is a similar transformation to the one in FoldAndOfFCmps.
1863 //
1864 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1865 // bool(R & CC0) || bool(R & CC1)
1866 // = bool((R & CC0) | (R & CC1))
1867 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1868 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1869 return getFCmpValue(getFCmpCode(Op0CC) | getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1870 Builder);
1871
Chris Lattner0a8191e2010-01-05 07:50:36 +00001872 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00001873 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001874 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1875 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1876 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1877 // If either of the constants are nans, then the whole thing returns
1878 // true.
1879 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001880 return Builder->getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00001881
Chris Lattner0a8191e2010-01-05 07:50:36 +00001882 // Otherwise, no need to compare the two constants, compare the
1883 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00001884 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001885 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001886
Chris Lattner0a8191e2010-01-05 07:50:36 +00001887 // Handle vector zeros. This occurs because the canonical form of
1888 // "fcmp uno x,x" is "fcmp uno x, 0".
1889 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1890 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001891 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00001892
Craig Topperf40110f2014-04-25 05:29:35 +00001893 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001894 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001895
Craig Topperf40110f2014-04-25 05:29:35 +00001896 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001897}
1898
Sanjay Patel18549272015-09-08 18:24:36 +00001899/// This helper function folds:
Chris Lattner0a8191e2010-01-05 07:50:36 +00001900///
1901/// ((A | B) & C1) | (B & C2)
1902///
1903/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00001904///
Chris Lattner0a8191e2010-01-05 07:50:36 +00001905/// (A & C1) | B
1906///
1907/// when the XOR of the two constants is "all ones" (-1).
Craig Toppera074c102017-06-21 18:57:00 +00001908static Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
1909 Value *A, Value *B, Value *C,
1910 InstCombiner::BuilderTy *Builder) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001911 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +00001912 if (!CI1) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001913
Craig Topperf40110f2014-04-25 05:29:35 +00001914 Value *V1 = nullptr;
1915 ConstantInt *CI2 = nullptr;
1916 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001917
1918 APInt Xor = CI1->getValue() ^ CI2->getValue();
Craig Topperf40110f2014-04-25 05:29:35 +00001919 if (!Xor.isAllOnesValue()) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001920
1921 if (V1 == A || V1 == B) {
1922 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1923 return BinaryOperator::CreateOr(NewOp, V1);
1924 }
1925
Craig Topperf40110f2014-04-25 05:29:35 +00001926 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001927}
1928
David Majnemer5d1aeba2014-08-21 05:14:48 +00001929/// \brief This helper function folds:
1930///
Craig Toppera074c102017-06-21 18:57:00 +00001931/// ((A ^ B) & C1) | (B & C2)
David Majnemer5d1aeba2014-08-21 05:14:48 +00001932///
1933/// into:
1934///
1935/// (A & C1) ^ B
1936///
1937/// when the XOR of the two constants is "all ones" (-1).
Craig Toppera074c102017-06-21 18:57:00 +00001938static Instruction *FoldXorWithConstants(BinaryOperator &I, Value *Op,
1939 Value *A, Value *B, Value *C,
1940 InstCombiner::BuilderTy *Builder) {
David Majnemer5d1aeba2014-08-21 05:14:48 +00001941 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1942 if (!CI1)
1943 return nullptr;
1944
1945 Value *V1 = nullptr;
1946 ConstantInt *CI2 = nullptr;
1947 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
1948 return nullptr;
1949
1950 APInt Xor = CI1->getValue() ^ CI2->getValue();
1951 if (!Xor.isAllOnesValue())
1952 return nullptr;
1953
1954 if (V1 == A || V1 == B) {
1955 Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
1956 return BinaryOperator::CreateXor(NewOp, V1);
1957 }
1958
1959 return nullptr;
1960}
1961
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001962// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1963// here. We should standardize that construct where it is needed or choose some
1964// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001965Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001966 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001967 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1968
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001969 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001970 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001971
Craig Toppera4205622017-06-09 03:21:29 +00001972 if (Value *V = SimplifyOrInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001973 return replaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00001974
Craig Topper9d4171a2012-12-20 07:09:41 +00001975 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001976 // purpose is to compute bits we don't care about.
1977 if (SimplifyDemandedInstructionBits(I))
1978 return &I;
1979
Sanjay Patele0c26e02017-04-23 22:00:02 +00001980 // Do this before using distributive laws to catch simple and/or/not patterns.
1981 if (Instruction *Xor = foldOrToXor(I, *Builder))
1982 return Xor;
1983
1984 // (A&B)|(A&C) -> A&(B|C) etc
1985 if (Value *V = SimplifyUsingDistributiveLaws(I))
1986 return replaceInstUsesWith(I, V);
1987
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001988 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001989 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001990
Craig Topper86173602017-04-04 20:26:25 +00001991 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001992 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1993 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001994
Chad Rosiere5819e22016-05-26 14:58:51 +00001995 // Given an OR instruction, check to see if this is a bswap.
1996 if (Instruction *BSwap = MatchBSwap(I))
1997 return BSwap;
1998
Craig Topperafa07c52017-04-09 06:12:41 +00001999 {
2000 Value *A;
2001 const APInt *C;
2002 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2003 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
2004 MaskedValueIsZero(Op1, *C, 0, &I)) {
2005 Value *NOr = Builder->CreateOr(A, Op1);
2006 NOr->takeName(Op0);
2007 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00002008 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00002009 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002010
Craig Topperafa07c52017-04-09 06:12:41 +00002011 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2012 if (match(Op1, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
2013 MaskedValueIsZero(Op0, *C, 0, &I)) {
2014 Value *NOr = Builder->CreateOr(A, Op0);
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 }
2020
Craig Topperafa07c52017-04-09 06:12:41 +00002021 Value *A, *B;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002022
Suyog Sardad64faf62014-07-22 18:09:41 +00002023 // ((~A & B) | A) -> (A | B)
Craig Topper72a622c2017-04-07 00:29:47 +00002024 if (match(Op0, m_c_And(m_Not(m_Specific(Op1)), m_Value(A))))
2025 return BinaryOperator::CreateOr(A, Op1);
2026 if (match(Op1, m_c_And(m_Not(m_Specific(Op0)), m_Value(A))))
2027 return BinaryOperator::CreateOr(Op0, A);
Suyog Sardad64faf62014-07-22 18:09:41 +00002028
2029 // ((A & B) | ~A) -> (~A | B)
Craig Topper33e0dbc2017-04-07 07:32:00 +00002030 // The NOT is guaranteed to be in the RHS by complexity ordering.
2031 if (match(Op1, m_Not(m_Value(A))) &&
2032 match(Op0, m_c_And(m_Specific(A), m_Value(B))))
2033 return BinaryOperator::CreateOr(Op1, B);
Suyog Sardad64faf62014-07-22 18:09:41 +00002034
Chris Lattner0a8191e2010-01-05 07:50:36 +00002035 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00002036 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002037 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2038 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperf40110f2014-04-25 05:29:35 +00002039 Value *V1 = nullptr, *V2 = nullptr;
Craig Topperafa07c52017-04-09 06:12:41 +00002040 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
2041 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002042 if (C1 && C2) { // (A & C1)|(B & C2)
Craig Topper73ba1c82017-06-07 07:40:37 +00002043 if ((C1->getValue() & C2->getValue()).isNullValue()) {
Chris Lattner95188692010-01-11 06:55:24 +00002044 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002045 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002046 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002047 ((V1 == B &&
2048 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2049 (V2 == B &&
2050 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002051 return BinaryOperator::CreateAnd(A,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002052 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002053 // Or commutes, try both ways.
2054 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002055 ((V1 == A &&
2056 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2057 (V2 == A &&
2058 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002059 return BinaryOperator::CreateAnd(B,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002060 Builder->getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002061
Chris Lattner95188692010-01-11 06:55:24 +00002062 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002063 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00002064 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00002065 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00002066 (C3->getValue() & ~C1->getValue()).isNullValue() &&
Chris Lattner95188692010-01-11 06:55:24 +00002067 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00002068 (C4->getValue() & ~C2->getValue()).isNullValue()) {
Chris Lattner95188692010-01-11 06:55:24 +00002069 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2070 return BinaryOperator::CreateAnd(V2,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002071 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002072 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002073 }
2074 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002075
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002076 // Don't try to form a select if it's unlikely that we'll get rid of at
2077 // least one of the operands. A select is generally more expensive than the
2078 // 'or' that it is replacing.
2079 if (Op0->hasOneUse() || Op1->hasOneUse()) {
2080 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
2081 if (Value *V = matchSelectFromAndOr(A, C, B, D, *Builder))
2082 return replaceInstUsesWith(I, V);
2083 if (Value *V = matchSelectFromAndOr(A, C, D, B, *Builder))
2084 return replaceInstUsesWith(I, V);
2085 if (Value *V = matchSelectFromAndOr(C, A, B, D, *Builder))
2086 return replaceInstUsesWith(I, V);
2087 if (Value *V = matchSelectFromAndOr(C, A, D, B, *Builder))
2088 return replaceInstUsesWith(I, V);
2089 if (Value *V = matchSelectFromAndOr(B, D, A, C, *Builder))
2090 return replaceInstUsesWith(I, V);
2091 if (Value *V = matchSelectFromAndOr(B, D, C, A, *Builder))
2092 return replaceInstUsesWith(I, V);
2093 if (Value *V = matchSelectFromAndOr(D, B, A, C, *Builder))
2094 return replaceInstUsesWith(I, V);
2095 if (Value *V = matchSelectFromAndOr(D, B, C, A, *Builder))
2096 return replaceInstUsesWith(I, V);
2097 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002098
Benjamin Kramer11743242010-07-12 13:34:22 +00002099 // ((A|B)&1)|(B&-2) -> (A&1) | B
Craig Toppera074c102017-06-21 18:57:00 +00002100 if (match(A, m_c_Or(m_Value(V1), m_Specific(B)))) {
2101 if (Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C, Builder))
2102 return Ret;
Benjamin Kramer11743242010-07-12 13:34:22 +00002103 }
2104 // (B&-2)|((A|B)&1) -> (A&1) | B
Craig Toppera074c102017-06-21 18:57:00 +00002105 if (match(B, m_c_Or(m_Specific(A), m_Value(V1)))) {
2106 if (Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D, Builder))
2107 return Ret;
Benjamin Kramer11743242010-07-12 13:34:22 +00002108 }
David Majnemer5d1aeba2014-08-21 05:14:48 +00002109 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
Craig Toppera074c102017-06-21 18:57:00 +00002110 if (match(A, m_c_Xor(m_Value(V1), m_Specific(B)))) {
2111 if (Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C, Builder))
2112 return Ret;
David Majnemer5d1aeba2014-08-21 05:14:48 +00002113 }
2114 // (B&-2)|((A^B)&1) -> (A&1) ^ B
Craig Toppera074c102017-06-21 18:57:00 +00002115 if (match(B, m_c_Xor(m_Specific(A), m_Value(V1)))) {
2116 if (Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D, Builder))
2117 return Ret;
David Majnemer5d1aeba2014-08-21 05:14:48 +00002118 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002119 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002120
David Majnemer42af3602014-07-30 21:26:37 +00002121 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2122 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2123 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00002124 return BinaryOperator::CreateOr(Op0, C);
David Majnemer42af3602014-07-30 21:26:37 +00002125
2126 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2127 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2128 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00002129 return BinaryOperator::CreateOr(Op1, C);
David Majnemer42af3602014-07-30 21:26:37 +00002130
David Majnemerf1eda232014-08-14 06:41:38 +00002131 // ((B | C) & A) | B -> B | (A & C)
2132 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2133 return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2134
Sanjay Patel7caaa792017-05-09 20:05:05 +00002135 if (Instruction *DeMorgan = matchDeMorgansLaws(I, *Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00002136 return DeMorgan;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002137
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002138 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002139 bool SwappedForXor = false;
2140 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002141 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002142 SwappedForXor = true;
2143 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002144
2145 // A | ( A ^ B) -> A | B
2146 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002147 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002148 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2149 if (Op0 == A || Op0 == B)
2150 return BinaryOperator::CreateOr(A, B);
2151
Chad Rosier7813dce2012-04-26 23:29:14 +00002152 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2153 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2154 return BinaryOperator::CreateOr(A, B);
2155
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002156 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2157 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2158 return BinaryOperator::CreateOr(Not, Op0);
2159 }
2160 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2161 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2162 return BinaryOperator::CreateOr(Not, Op0);
2163 }
2164 }
2165
2166 // A | ~(A | B) -> A | ~B
2167 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002168 if (match(Op1, m_Not(m_Value(A))))
2169 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002170 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2171 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2172 B->getOpcode() == Instruction::Xor)) {
2173 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2174 B->getOperand(0);
2175 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2176 return BinaryOperator::CreateOr(Not, Op0);
2177 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002178
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002179 // (A & B) | (~A ^ B) -> (~A ^ B)
2180 // (A & B) | (B ^ ~A) -> (~A ^ B)
2181 // (B & A) | (~A ^ B) -> (~A ^ B)
2182 // (B & A) | (B ^ ~A) -> (~A ^ B)
2183 // The match order is important: match the xor first because the 'not'
2184 // operation defines 'A'. We do not need to match the xor as Op0 because the
2185 // xor was canonicalized to Op1 above.
2186 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2187 match(Op0, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sarda16d64652014-08-01 04:41:43 +00002188 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2189
Eli Friedmane06535b2012-03-16 00:52:42 +00002190 if (SwappedForXor)
2191 std::swap(Op0, Op1);
2192
David Majnemer3d6f80b2014-11-28 19:58:29 +00002193 {
2194 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2195 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2196 if (LHS && RHS)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002197 if (Value *Res = foldOrOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002198 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002199
David Majnemer3d6f80b2014-11-28 19:58:29 +00002200 // TODO: Make this recursive; it's a little tricky because an arbitrary
2201 // number of 'or' instructions might have to be created.
2202 Value *X, *Y;
2203 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2204 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002205 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002206 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002207 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002208 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002209 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002210 }
2211 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2212 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002213 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002214 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002215 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002216 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002217 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002218 }
2219 }
2220
Chris Lattner4e8137d2010-02-11 06:26:33 +00002221 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2222 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2223 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel5e456b92017-05-18 20:53:16 +00002224 if (Value *Res = foldOrOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00002225 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002226
Sanjay Patel75b4ae22016-02-23 23:56:23 +00002227 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2228 return CastedOr;
Eli Friedman23956262011-04-14 22:41:27 +00002229
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002230 // 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 +00002231 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002232 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002233 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
Sanjay Patel1b6b8242016-07-08 17:26:47 +00002234 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002235 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002236 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2237
Owen Andersonc237a842010-09-13 17:59:27 +00002238 // Note: If we've gotten to the point of visiting the outer OR, then the
2239 // inner one couldn't be simplified. If it was a constant, then it won't
2240 // be simplified by a later pass either, so we try swapping the inner/outer
2241 // ORs in the hopes that we'll be able to simplify it this way.
2242 // (X|C) | V --> (X|V) | C
Craig Topperafa07c52017-04-09 06:12:41 +00002243 ConstantInt *C1;
Owen Andersonc237a842010-09-13 17:59:27 +00002244 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2245 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2246 Value *Inner = Builder->CreateOr(A, Op1);
2247 Inner->takeName(Op0);
2248 return BinaryOperator::CreateOr(Inner, C1);
2249 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002250
Bill Wendling23242092013-02-16 23:41:36 +00002251 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2252 // Since this OR statement hasn't been optimized further yet, we hope
2253 // that this transformation will allow the new ORs to be optimized.
2254 {
Craig Topperf40110f2014-04-25 05:29:35 +00002255 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002256 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2257 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2258 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2259 Value *orTrue = Builder->CreateOr(A, C);
2260 Value *orFalse = Builder->CreateOr(B, D);
2261 return SelectInst::Create(X, orTrue, orFalse);
2262 }
2263 }
2264
Craig Topperf40110f2014-04-25 05:29:35 +00002265 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002266}
2267
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002268/// A ^ B can be specified using other logic ops in a variety of patterns. We
2269/// can fold these early and efficiently by morphing an existing instruction.
Craig Topperf60ab472017-07-02 01:15:51 +00002270static Instruction *foldXorToXor(BinaryOperator &I,
2271 InstCombiner::BuilderTy &Builder) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002272 assert(I.getOpcode() == Instruction::Xor);
2273 Value *Op0 = I.getOperand(0);
2274 Value *Op1 = I.getOperand(1);
2275 Value *A, *B;
2276
2277 // There are 4 commuted variants for each of the basic patterns.
2278
2279 // (A & B) ^ (A | B) -> A ^ B
2280 // (A & B) ^ (B | A) -> A ^ B
2281 // (A | B) ^ (A & B) -> A ^ B
2282 // (A | B) ^ (B & A) -> A ^ B
2283 if ((match(Op0, m_And(m_Value(A), m_Value(B))) &&
2284 match(Op1, m_c_Or(m_Specific(A), m_Specific(B)))) ||
2285 (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2286 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))) {
2287 I.setOperand(0, A);
2288 I.setOperand(1, B);
2289 return &I;
2290 }
2291
2292 // (A | ~B) ^ (~A | B) -> A ^ B
2293 // (~B | A) ^ (~A | B) -> A ^ B
2294 // (~A | B) ^ (A | ~B) -> A ^ B
2295 // (B | ~A) ^ (A | ~B) -> A ^ B
Craig Topper880bf822017-06-30 07:37:41 +00002296 if ((match(Op0, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2297 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B)))) ||
2298 (match(Op0, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2299 match(Op1, m_c_Or(m_Specific(A), m_Not(m_Specific(B)))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002300 I.setOperand(0, A);
2301 I.setOperand(1, B);
2302 return &I;
2303 }
2304
2305 // (A & ~B) ^ (~A & B) -> A ^ B
2306 // (~B & A) ^ (~A & B) -> A ^ B
2307 // (~A & B) ^ (A & ~B) -> A ^ B
2308 // (B & ~A) ^ (A & ~B) -> A ^ B
Craig Topper880bf822017-06-30 07:37:41 +00002309 if ((match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2310 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))) ||
2311 (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2312 match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002313 I.setOperand(0, A);
2314 I.setOperand(1, B);
2315 return &I;
2316 }
2317
Craig Topperf60ab472017-07-02 01:15:51 +00002318 // For the remaining cases we need to get rid of one of the operands.
2319 if (!Op0->hasOneUse() && !Op1->hasOneUse())
2320 return nullptr;
2321
2322 // (A | B) ^ ~(A & B) -> ~(A ^ B)
2323 // (A | B) ^ ~(B & A) -> ~(A ^ B)
2324 // (A & B) ^ ~(A | B) -> ~(A ^ B)
2325 // (A & B) ^ ~(B | A) -> ~(A ^ B)
2326 // Complexity sorting ensures the not will be on the right side.
2327 if ((match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2328 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) ||
2329 (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2330 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))))
2331 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
2332
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002333 return nullptr;
2334}
2335
Sanjay Patel5e456b92017-05-18 20:53:16 +00002336Value *InstCombiner::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
2337 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2338 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2339 LHS->getOperand(1) == RHS->getOperand(0))
2340 LHS->swapOperands();
2341 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2342 LHS->getOperand(1) == RHS->getOperand(1)) {
2343 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2344 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2345 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2346 bool isSigned = LHS->isSigned() || RHS->isSigned();
2347 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
2348 }
2349 }
2350
Sanjay Pateladca8252017-06-20 12:40:55 +00002351 // Instead of trying to imitate the folds for and/or, decompose this 'xor'
2352 // into those logic ops. That is, try to turn this into an and-of-icmps
2353 // because we have many folds for that pattern.
2354 //
2355 // This is based on a truth table definition of xor:
2356 // X ^ Y --> (X | Y) & !(X & Y)
2357 if (Value *OrICmp = SimplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
2358 // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
2359 // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
2360 if (Value *AndICmp = SimplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
2361 // TODO: Independently handle cases where the 'and' side is a constant.
2362 if (OrICmp == LHS && AndICmp == RHS && RHS->hasOneUse()) {
2363 // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS
2364 RHS->setPredicate(RHS->getInversePredicate());
2365 return Builder->CreateAnd(LHS, RHS);
2366 }
2367 if (OrICmp == RHS && AndICmp == LHS && LHS->hasOneUse()) {
Sanjay Patel4ccbd582017-06-20 12:45:46 +00002368 // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS
Sanjay Pateladca8252017-06-20 12:40:55 +00002369 LHS->setPredicate(LHS->getInversePredicate());
2370 return Builder->CreateAnd(LHS, RHS);
2371 }
2372 }
2373 }
2374
Sanjay Patel5e456b92017-05-18 20:53:16 +00002375 return nullptr;
2376}
2377
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002378// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2379// here. We should standardize that construct where it is needed or choose some
2380// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002381Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002382 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002383 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2384
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002385 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002386 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002387
Craig Toppera4205622017-06-09 03:21:29 +00002388 if (Value *V = SimplifyXorInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002389 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002390
Craig Topperf60ab472017-07-02 01:15:51 +00002391 if (Instruction *NewXor = foldXorToXor(I, *Builder))
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002392 return NewXor;
2393
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002394 // (A&B)^(A&C) -> A&(B^C) etc
2395 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002396 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002397
Craig Topper9d4171a2012-12-20 07:09:41 +00002398 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002399 // purpose is to compute bits we don't care about.
2400 if (SimplifyDemandedInstructionBits(I))
2401 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002402
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002403 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002404 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002405
Sanjay Patel6381db12017-05-02 15:31:40 +00002406 // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
2407 Value *X, *Y;
2408
2409 // We must eliminate the and/or (one-use) for these transforms to not increase
2410 // the instruction count.
2411 // ~(~X & Y) --> (X | ~Y)
2412 // ~(Y & ~X) --> (X | ~Y)
2413 if (match(&I, m_Not(m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y)))))) {
2414 Value *NotY = Builder->CreateNot(Y, Y->getName() + ".not");
2415 return BinaryOperator::CreateOr(X, NotY);
2416 }
2417 // ~(~X | Y) --> (X & ~Y)
2418 // ~(Y | ~X) --> (X & ~Y)
2419 if (match(&I, m_Not(m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y)))))) {
2420 Value *NotY = Builder->CreateNot(Y, Y->getName() + ".not");
2421 return BinaryOperator::CreateAnd(X, NotY);
2422 }
2423
Sanjay Patel3b863f82017-04-22 18:05:35 +00002424 // Is this a 'not' (~) fed by a binary operator?
Sanjay Patela1c88142017-05-08 20:49:59 +00002425 BinaryOperator *NotVal;
2426 if (match(&I, m_Not(m_BinOp(NotVal)))) {
2427 if (NotVal->getOpcode() == Instruction::And ||
2428 NotVal->getOpcode() == Instruction::Or) {
Sanjay Patel6381db12017-05-02 15:31:40 +00002429 // Apply DeMorgan's Law when inverts are free:
2430 // ~(X & Y) --> (~X | ~Y)
2431 // ~(X | Y) --> (~X & ~Y)
Sanjay Patela1c88142017-05-08 20:49:59 +00002432 if (IsFreeToInvert(NotVal->getOperand(0),
2433 NotVal->getOperand(0)->hasOneUse()) &&
2434 IsFreeToInvert(NotVal->getOperand(1),
2435 NotVal->getOperand(1)->hasOneUse())) {
2436 Value *NotX = Builder->CreateNot(NotVal->getOperand(0), "notlhs");
2437 Value *NotY = Builder->CreateNot(NotVal->getOperand(1), "notrhs");
2438 if (NotVal->getOpcode() == Instruction::And)
Sanjay Patel3b863f82017-04-22 18:05:35 +00002439 return BinaryOperator::CreateOr(NotX, NotY);
2440 return BinaryOperator::CreateAnd(NotX, NotY);
2441 }
Sanjay Patela1c88142017-05-08 20:49:59 +00002442 }
2443
2444 // ~(~X >>s Y) --> (X >>s Y)
2445 if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
2446 return BinaryOperator::CreateAShr(X, Y);
2447
2448 // If we are inverting a right-shifted constant, we may be able to eliminate
2449 // the 'not' by inverting the constant and using the opposite shift type.
2450 // Canonicalization rules ensure that only a negative constant uses 'ashr',
2451 // but we must check that in case that transform has not fired yet.
2452 const APInt *C;
2453 if (match(NotVal, m_AShr(m_APInt(C), m_Value(Y))) && C->isNegative()) {
2454 // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
2455 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2456 return BinaryOperator::CreateLShr(NotC, Y);
2457 }
2458
2459 if (match(NotVal, m_LShr(m_APInt(C), m_Value(Y))) && C->isNonNegative()) {
2460 // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
2461 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2462 return BinaryOperator::CreateAShr(NotC, Y);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002463 }
2464 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002465
Craig Topper798a19a2017-06-29 00:07:08 +00002466 // not (cmp A, B) = !cmp A, B
Craig Toppercc418b62017-07-05 20:31:00 +00002467 CmpInst::Predicate Pred;
Craig Topper798a19a2017-06-29 00:07:08 +00002468 if (match(&I, m_Not(m_OneUse(m_Cmp(Pred, m_Value(), m_Value()))))) {
Sanjay Patel33439f92017-04-12 15:11:33 +00002469 cast<CmpInst>(Op0)->setPredicate(CmpInst::getInversePredicate(Pred));
2470 return replaceInstUsesWith(I, Op0);
Benjamin Kramer443c7962015-02-12 20:26:46 +00002471 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002472
Craig Topper9d1821b2017-04-09 06:12:31 +00002473 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002474 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2475 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2476 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2477 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2478 Instruction::CastOps Opcode = Op0C->getOpcode();
2479 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Craig Topper9d1821b2017-04-09 06:12:31 +00002480 (RHSC == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Chris Lattner0a8191e2010-01-05 07:50:36 +00002481 Op0C->getDestTy()))) {
2482 CI->setPredicate(CI->getInversePredicate());
2483 return CastInst::Create(Opcode, CI, Op0C->getType());
2484 }
2485 }
2486 }
2487 }
2488
2489 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2490 // ~(c-X) == X-c-1 == X+(-c-1)
Craig Topper9d1821b2017-04-09 06:12:31 +00002491 if (Op0I->getOpcode() == Instruction::Sub && RHSC->isAllOnesValue())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002492 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2493 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
Craig Topper437c9762017-04-09 06:12:34 +00002494 return BinaryOperator::CreateAdd(Op0I->getOperand(1),
2495 SubOne(NegOp0I0C));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002496 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002497
Chris Lattner0a8191e2010-01-05 07:50:36 +00002498 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2499 if (Op0I->getOpcode() == Instruction::Add) {
2500 // ~(X-c) --> (-c-1)-X
Craig Topper9d1821b2017-04-09 06:12:31 +00002501 if (RHSC->isAllOnesValue()) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002502 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Craig Topper437c9762017-04-09 06:12:34 +00002503 return BinaryOperator::CreateSub(SubOne(NegOp0CI),
2504 Op0I->getOperand(0));
Craig Topperbcfd2d12017-04-20 16:56:25 +00002505 } else if (RHSC->getValue().isSignMask()) {
2506 // (X + C) ^ signmask -> (X + C + signmask)
Craig Topper9d1821b2017-04-09 06:12:31 +00002507 Constant *C = Builder->getInt(RHSC->getValue() + Op0CI->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002508 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2509
2510 }
2511 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002512 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Hal Finkel60db0582014-09-07 18:57:58 +00002513 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2514 0, &I)) {
Craig Topper9d1821b2017-04-09 06:12:31 +00002515 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002516 // Anything in both C1 and C2 is known to be zero, remove it from
2517 // NewRHS.
Craig Topper9d1821b2017-04-09 06:12:31 +00002518 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHSC);
Craig Topper9d4171a2012-12-20 07:09:41 +00002519 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002520 ConstantExpr::getNot(CommonBits));
2521 Worklist.Add(Op0I);
2522 I.setOperand(0, Op0I->getOperand(0));
2523 I.setOperand(1, NewRHS);
2524 return &I;
2525 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002526 } else if (Op0I->getOpcode() == Instruction::LShr) {
2527 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2528 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002529 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002530 ConstantInt *C1;
2531 if (Op0I->hasOneUse() &&
2532 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2533 E1->getOpcode() == Instruction::Xor &&
2534 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2535 // fold (C1 >> C2) ^ C3
Craig Topper9d1821b2017-04-09 06:12:31 +00002536 ConstantInt *C2 = Op0CI, *C3 = RHSC;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002537 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2538 FoldConst ^= C3->getValue();
2539 // Prepare the two operands.
2540 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2541 Opnd0->takeName(Op0I);
2542 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2543 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2544
2545 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2546 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002547 }
2548 }
2549 }
Craig Topper86173602017-04-04 20:26:25 +00002550 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002551
Craig Topper86173602017-04-04 20:26:25 +00002552 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00002553 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2554 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002555
Craig Topper76394602017-04-10 06:53:23 +00002556 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002557 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002558 if (match(Op1, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Craig Topper47383212017-04-10 06:53:21 +00002559 if (A == Op0) { // A^(A|B) == A^(B|A)
Craig Topper76394602017-04-10 06:53:23 +00002560 cast<BinaryOperator>(Op1)->swapOperands();
Craig Topper47383212017-04-10 06:53:21 +00002561 std::swap(A, B);
2562 }
2563 if (B == Op0) { // A^(B|A) == (B|A)^A
Chris Lattner0a8191e2010-01-05 07:50:36 +00002564 I.swapOperands(); // Simplified below.
2565 std::swap(Op0, Op1);
2566 }
Craig Topper76394602017-04-10 06:53:23 +00002567 } else if (match(Op1, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002568 if (A == Op0) { // A^(A&B) -> A^(B&A)
Craig Topper76394602017-04-10 06:53:23 +00002569 cast<BinaryOperator>(Op1)->swapOperands();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002570 std::swap(A, B);
2571 }
2572 if (B == Op0) { // A^(B&A) -> (B&A)^A
2573 I.swapOperands(); // Simplified below.
2574 std::swap(Op0, Op1);
2575 }
2576 }
2577 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002578
Craig Topper76394602017-04-10 06:53:23 +00002579 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002580 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002581 if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002582 if (A == Op1) // (B|A)^B == (A|B)^B
2583 std::swap(A, B);
2584 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002585 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper76394602017-04-10 06:53:23 +00002586 } else if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002587 if (A == Op1) // (A&B)^A -> (B&A)^A
2588 std::swap(A, B);
Craig Toppere63c21b2017-04-09 06:12:39 +00002589 const APInt *C;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002590 if (B == Op1 && // (B&A)^A == ~B & A
Craig Toppere63c21b2017-04-09 06:12:39 +00002591 !match(Op1, m_APInt(C))) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002592 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002593 }
2594 }
2595 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002596
Craig Topper76394602017-04-10 06:53:23 +00002597 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002598 Value *A, *B, *C, *D;
David Majnemer6fe6ea72014-09-05 06:09:24 +00002599 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002600 if (match(Op0, m_Xor(m_Value(D), m_Value(C))) &&
2601 match(Op1, m_Or(m_Value(A), m_Value(B)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002602 if (D == A)
2603 return BinaryOperator::CreateXor(
2604 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2605 if (D == B)
2606 return BinaryOperator::CreateXor(
2607 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002608 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002609 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002610 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2611 match(Op1, m_Xor(m_Value(D), m_Value(C)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002612 if (D == A)
2613 return BinaryOperator::CreateXor(
2614 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2615 if (D == B)
2616 return BinaryOperator::CreateXor(
2617 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002618 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002619 // (A & B) ^ (A ^ B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002620 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002621 match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002622 return BinaryOperator::CreateOr(A, B);
2623 // (A ^ B) ^ (A & B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002624 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002625 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002626 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002627 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002628
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002629 // (A & ~B) ^ ~A -> ~(A & B)
2630 // (~B & A) ^ ~A -> ~(A & B)
2631 Value *A, *B;
2632 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
Suyog Sarda56c9a872014-08-01 05:07:20 +00002633 match(Op1, m_Not(m_Specific(A))))
2634 return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2635
Sanjay Patel5e456b92017-05-18 20:53:16 +00002636 if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2637 if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2638 if (Value *V = foldXorOfICmps(LHS, RHS))
2639 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002640
Sanjay Pateldbbaca02016-02-24 17:00:34 +00002641 if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2642 return CastedXor;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002643
Craig Topperf40110f2014-04-25 05:29:35 +00002644 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002645}