blob: 5f16284631e041ae54fab207c175ef13f585e81e [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
Chris Lattner0a8191e2010-01-05 07:50:36 +000026static inline Value *dyn_castNotVal(Value *V) {
27 // If this is not(not(x)) don't return that this is a not: we want the two
28 // not's to be folded first.
29 if (BinaryOperator::isNot(V)) {
30 Value *Operand = BinaryOperator::getNotArgument(V);
Sanjoy Das82ea3d42015-02-24 00:08:41 +000031 if (!IsFreeToInvert(Operand, Operand->hasOneUse()))
Chris Lattner0a8191e2010-01-05 07:50:36 +000032 return Operand;
33 }
Craig Topper9d4171a2012-12-20 07:09:41 +000034
Chris Lattner0a8191e2010-01-05 07:50:36 +000035 // Constants can be considered to be not'ed values...
36 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
37 return ConstantInt::get(C->getType(), ~C->getValue());
Craig Topperf40110f2014-04-25 05:29:35 +000038 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +000039}
40
Sanjay Patel18549272015-09-08 18:24:36 +000041/// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
Tim Shenaec68b22016-06-29 20:10:17 +000042/// a four bit mask.
43static unsigned getFCmpCode(FCmpInst::Predicate CC) {
44 assert(FCmpInst::FCMP_FALSE <= CC && CC <= FCmpInst::FCMP_TRUE &&
45 "Unexpected FCmp predicate!");
46 // Take advantage of the bit pattern of FCmpInst::Predicate here.
47 // U L G E
48 static_assert(FCmpInst::FCMP_FALSE == 0, ""); // 0 0 0 0
49 static_assert(FCmpInst::FCMP_OEQ == 1, ""); // 0 0 0 1
50 static_assert(FCmpInst::FCMP_OGT == 2, ""); // 0 0 1 0
51 static_assert(FCmpInst::FCMP_OGE == 3, ""); // 0 0 1 1
52 static_assert(FCmpInst::FCMP_OLT == 4, ""); // 0 1 0 0
53 static_assert(FCmpInst::FCMP_OLE == 5, ""); // 0 1 0 1
54 static_assert(FCmpInst::FCMP_ONE == 6, ""); // 0 1 1 0
55 static_assert(FCmpInst::FCMP_ORD == 7, ""); // 0 1 1 1
56 static_assert(FCmpInst::FCMP_UNO == 8, ""); // 1 0 0 0
57 static_assert(FCmpInst::FCMP_UEQ == 9, ""); // 1 0 0 1
58 static_assert(FCmpInst::FCMP_UGT == 10, ""); // 1 0 1 0
59 static_assert(FCmpInst::FCMP_UGE == 11, ""); // 1 0 1 1
60 static_assert(FCmpInst::FCMP_ULT == 12, ""); // 1 1 0 0
61 static_assert(FCmpInst::FCMP_ULE == 13, ""); // 1 1 0 1
62 static_assert(FCmpInst::FCMP_UNE == 14, ""); // 1 1 1 0
63 static_assert(FCmpInst::FCMP_TRUE == 15, ""); // 1 1 1 1
64 return CC;
Chris Lattner0a8191e2010-01-05 07:50:36 +000065}
66
Sanjay Patel18549272015-09-08 18:24:36 +000067/// This is the complement of getICmpCode, which turns an opcode and two
68/// operands into either a constant true or false, or a brand new ICmp
69/// instruction. The sign is passed in to determine which kind of predicate to
70/// use in the new icmp instruction.
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000071static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
72 InstCombiner::BuilderTy *Builder) {
Pete Cooperebf98c12011-12-17 01:20:32 +000073 ICmpInst::Predicate NewPred;
74 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
75 return NewConstant;
76 return Builder->CreateICmp(NewPred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000077}
78
Sanjay Patel18549272015-09-08 18:24:36 +000079/// This is the complement of getFCmpCode, which turns an opcode and two
Tim Shenaec68b22016-06-29 20:10:17 +000080/// operands into either a FCmp instruction, or a true/false constant.
81static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
Chris Lattner067459c2010-03-05 08:46:26 +000082 InstCombiner::BuilderTy *Builder) {
Tim Shenaec68b22016-06-29 20:10:17 +000083 const auto Pred = static_cast<FCmpInst::Predicate>(Code);
84 assert(FCmpInst::FCMP_FALSE <= Pred && Pred <= FCmpInst::FCMP_TRUE &&
85 "Unexpected FCmp predicate!");
86 if (Pred == FCmpInst::FCMP_FALSE)
87 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
88 if (Pred == FCmpInst::FCMP_TRUE)
89 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Chris Lattner067459c2010-03-05 08:46:26 +000090 return Builder->CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000091}
92
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000093/// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) to BSWAP(BITWISE_OP(A, B))
94/// \param I Binary operator to transform.
95/// \return Pointer to node that must replace the original binary operator, or
96/// null pointer if no transformation was made.
97Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
98 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
99
100 // Can't do vectors.
Sanjay Patel1e6ca442016-11-22 22:54:36 +0000101 if (I.getType()->isVectorTy())
102 return nullptr;
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000103
104 // Can only do bitwise ops.
Sanjay Patel1e6ca442016-11-22 22:54:36 +0000105 if (!I.isBitwiseLogicOp())
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000106 return nullptr;
107
108 Value *OldLHS = I.getOperand(0);
109 Value *OldRHS = I.getOperand(1);
110 ConstantInt *ConstLHS = dyn_cast<ConstantInt>(OldLHS);
111 ConstantInt *ConstRHS = dyn_cast<ConstantInt>(OldRHS);
112 IntrinsicInst *IntrLHS = dyn_cast<IntrinsicInst>(OldLHS);
113 IntrinsicInst *IntrRHS = dyn_cast<IntrinsicInst>(OldRHS);
114 bool IsBswapLHS = (IntrLHS && IntrLHS->getIntrinsicID() == Intrinsic::bswap);
115 bool IsBswapRHS = (IntrRHS && IntrRHS->getIntrinsicID() == Intrinsic::bswap);
116
117 if (!IsBswapLHS && !IsBswapRHS)
118 return nullptr;
119
120 if (!IsBswapLHS && !ConstLHS)
121 return nullptr;
122
123 if (!IsBswapRHS && !ConstRHS)
124 return nullptr;
125
126 /// OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
127 /// OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
128 Value *NewLHS = IsBswapLHS ? IntrLHS->getOperand(0) :
129 Builder->getInt(ConstLHS->getValue().byteSwap());
130
131 Value *NewRHS = IsBswapRHS ? IntrRHS->getOperand(0) :
132 Builder->getInt(ConstRHS->getValue().byteSwap());
133
Sanjay Patel1e6ca442016-11-22 22:54:36 +0000134 Value *BinOp = Builder->CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000135 Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap, ITy);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000136 return Builder->CreateCall(F, BinOp);
137}
138
Sanjay Patel18549272015-09-08 18:24:36 +0000139/// This handles expressions of the form ((val OP C1) & C2). Where
Craig Topper70e4f432017-04-02 17:57:30 +0000140/// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.
141Instruction *InstCombiner::OptAndOp(BinaryOperator *Op,
Chris Lattner0a8191e2010-01-05 07:50:36 +0000142 ConstantInt *OpRHS,
143 ConstantInt *AndRHS,
144 BinaryOperator &TheAnd) {
145 Value *X = Op->getOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +0000146 Constant *Together = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000147 if (!Op->isShift())
148 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
149
150 switch (Op->getOpcode()) {
Craig Topper70e4f432017-04-02 17:57:30 +0000151 default: break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000152 case Instruction::Xor:
153 if (Op->hasOneUse()) {
154 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
155 Value *And = Builder->CreateAnd(X, AndRHS);
156 And->takeName(Op);
157 return BinaryOperator::CreateXor(And, Together);
158 }
159 break;
160 case Instruction::Or:
Owen Andersonc237a842010-09-13 17:59:27 +0000161 if (Op->hasOneUse()){
Owen Andersonc237a842010-09-13 17:59:27 +0000162 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
163 if (TogetherCI && !TogetherCI->isZero()){
164 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
165 // NOTE: This reduces the number of bits set in the & mask, which
166 // can expose opportunities for store narrowing.
167 Together = ConstantExpr::getXor(AndRHS, Together);
168 Value *And = Builder->CreateAnd(X, Together);
169 And->takeName(Op);
170 return BinaryOperator::CreateOr(And, OpRHS);
171 }
Chris Lattner0a8191e2010-01-05 07:50:36 +0000172 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000173
Chris Lattner0a8191e2010-01-05 07:50:36 +0000174 break;
175 case Instruction::Add:
176 if (Op->hasOneUse()) {
177 // Adding a one to a single bit bit-field should be turned into an XOR
178 // of the bit. First thing to check is to see if this AND is with a
179 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000180 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000181
182 // If there is only one bit set.
183 if (AndRHSV.isPowerOf2()) {
184 // Ok, at this point, we know that we are masking the result of the
185 // ADD down to exactly one bit. If the constant we are adding has
186 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000187 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000188
189 // Check to see if any bits below the one bit set in AndRHSV are set.
190 if ((AddRHS & (AndRHSV-1)) == 0) {
191 // If not, the only thing that can effect the output of the AND is
192 // the bit specified by AndRHSV. If that bit is set, the effect of
193 // the XOR is to toggle the bit. If it is clear, then the ADD has
194 // no effect.
195 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
196 TheAnd.setOperand(0, X);
197 return &TheAnd;
198 } else {
199 // Pull the XOR out of the AND.
200 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
201 NewAnd->takeName(Op);
202 return BinaryOperator::CreateXor(NewAnd, AndRHS);
203 }
204 }
205 }
206 }
207 break;
208
209 case Instruction::Shl: {
210 // We know that the AND will not produce any of the bits shifted in, so if
211 // the anded constant includes them, clear them now!
212 //
213 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
214 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
215 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000216 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000217
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000218 if (CI->getValue() == ShlMask)
219 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000220 return replaceInstUsesWith(TheAnd, Op); // No need for the and.
Craig Topper9d4171a2012-12-20 07:09:41 +0000221
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000222 if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner0a8191e2010-01-05 07:50:36 +0000223 TheAnd.setOperand(1, CI);
224 return &TheAnd;
225 }
226 break;
227 }
228 case Instruction::LShr: {
229 // We know that the AND will not produce any of the bits shifted in, so if
230 // the anded constant includes them, clear them now! This only applies to
231 // unsigned shifts, because a signed shr may bring in set bits!
232 //
233 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
234 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
235 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000236 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000237
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000238 if (CI->getValue() == ShrMask)
239 // Masking out bits that the shift already masks.
Sanjay Patel4b198802016-02-01 22:23:39 +0000240 return replaceInstUsesWith(TheAnd, Op);
Craig Topper9d4171a2012-12-20 07:09:41 +0000241
Chris Lattner9f0ac0d2011-02-15 01:56:08 +0000242 if (CI != AndRHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000243 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
244 return &TheAnd;
245 }
246 break;
247 }
248 case Instruction::AShr:
249 // Signed shr.
250 // See if this is shifting in some sign extension, then masking it out
251 // with an and.
252 if (Op->hasOneUse()) {
253 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
254 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
255 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Jakub Staszak461d1fe2013-06-06 00:37:23 +0000256 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000257 if (C == AndRHS) { // Masking out bits shifted in.
258 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
259 // Make the argument unsigned.
260 Value *ShVal = Op->getOperand(0);
261 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
262 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
263 }
264 }
265 break;
266 }
Craig Topperf40110f2014-04-25 05:29:35 +0000267 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000268}
269
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000270/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000271/// (V < Lo || V >= Hi). This method expects that Lo <= Hi. IsSigned indicates
272/// whether to treat V, Lo, and Hi as signed or not.
Sanjay Patel85d79742016-08-31 19:49:56 +0000273Value *InstCombiner::insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
Chris Lattner067459c2010-03-05 08:46:26 +0000274 bool isSigned, bool Inside) {
Sanjay Patel85d79742016-08-31 19:49:56 +0000275 assert((isSigned ? Lo.sle(Hi) : Lo.ule(Hi)) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000276 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000277
Sanjay Patel85d79742016-08-31 19:49:56 +0000278 Type *Ty = V->getType();
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000279 if (Lo == Hi)
Sanjay Patel85d79742016-08-31 19:49:56 +0000280 return Inside ? ConstantInt::getFalse(Ty) : ConstantInt::getTrue(Ty);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000281
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000282 // V >= Min && V < Hi --> V < Hi
283 // V < Min || V >= Hi --> V >= Hi
284 ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
Sanjay Patel85d79742016-08-31 19:49:56 +0000285 if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000286 Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
Sanjay Patel85d79742016-08-31 19:49:56 +0000287 return Builder->CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000288 }
289
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000290 // V >= Lo && V < Hi --> V - Lo u< Hi - Lo
291 // V < Lo || V >= Hi --> V - Lo u>= Hi - Lo
Sanjay Patel85d79742016-08-31 19:49:56 +0000292 Value *VMinusLo =
293 Builder->CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
294 Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000295 return Builder->CreateICmp(Pred, VMinusLo, HiMinusLo);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000296}
297
Craig Topper79120e82017-04-03 17:22:23 +0000298/// Returns true iff Val consists of one contiguous run of 1s with any number
299/// of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
300/// so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
301/// not, since all 1s are not contiguous.
302static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
303 const APInt& V = Val->getValue();
304 uint32_t BitWidth = Val->getType()->getBitWidth();
305 if (!V.isShiftedMask()) return false;
306
307 // look for the first zero bit after the run of ones
308 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
309 // look for the first non-zero bit
310 ME = V.getActiveBits();
311 return true;
312}
313
314/// This is part of an expression (LHS +/- RHS) & Mask, where isSub determines
315/// whether the operator is a sub. If we can fold one of the following xforms:
316///
317/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
318/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
319/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
320///
321/// return (A +/- B).
322///
323Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
324 ConstantInt *Mask, bool isSub,
325 Instruction &I) {
326 Instruction *LHSI = dyn_cast<Instruction>(LHS);
327 if (!LHSI || LHSI->getNumOperands() != 2 ||
328 !isa<ConstantInt>(LHSI->getOperand(1))) return nullptr;
329
330 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
331
332 switch (LHSI->getOpcode()) {
333 default: return nullptr;
334 case Instruction::And:
335 if (ConstantExpr::getAnd(N, Mask) == Mask) {
336 // If the AndRHS is a power of two minus one (0+1+), this is simple.
337 if ((Mask->getValue().countLeadingZeros() +
338 Mask->getValue().countPopulation()) ==
339 Mask->getValue().getBitWidth())
340 break;
341
342 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
343 // part, we don't need any explicit masks to take them out of A. If that
344 // is all N is, ignore it.
345 uint32_t MB = 0, ME = 0;
346 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
347 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
348 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
349 if (MaskedValueIsZero(RHS, Mask, 0, &I))
350 break;
351 }
352 }
353 return nullptr;
354 case Instruction::Or:
355 case Instruction::Xor:
356 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
357 if ((Mask->getValue().countLeadingZeros() +
358 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
359 && ConstantExpr::getAnd(N, Mask)->isNullValue())
360 break;
361 return nullptr;
362 }
363
364 if (isSub)
365 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
366 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
367}
368
Sanjay Patel77bf6222017-04-03 16:53:12 +0000369/// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
370/// that can be simplified.
371/// One of A and B is considered the mask. The other is the value. This is
372/// described as the "AMask" or "BMask" part of the enum. If the enum contains
373/// only "Mask", then both A and B can be considered masks. If A is the mask,
374/// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
375/// If both A and C are constants, this proof is also easy.
376/// For the following explanations, we assume that A is the mask.
377///
378/// "AllOnes" declares that the comparison is true only if (A & B) == A or all
379/// bits of A are set in B.
380/// Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
381///
382/// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
383/// bits of A are cleared in B.
384/// Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
385///
386/// "Mixed" declares that (A & B) == C and C might or might not contain any
387/// number of one bits and zero bits.
388/// Example: (icmp eq (A & 3), 1) -> AMask_Mixed
389///
390/// "Not" means that in above descriptions "==" should be replaced by "!=".
391/// Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
392///
Owen Anderson3fe002d2010-09-08 22:16:17 +0000393/// If the mask A contains a single bit, then the following is equivalent:
394/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
395/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
396enum MaskedICmpType {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000397 AMask_AllOnes = 1,
398 AMask_NotAllOnes = 2,
399 BMask_AllOnes = 4,
400 BMask_NotAllOnes = 8,
401 Mask_AllZeros = 16,
402 Mask_NotAllZeros = 32,
403 AMask_Mixed = 64,
404 AMask_NotMixed = 128,
405 BMask_Mixed = 256,
406 BMask_NotMixed = 512
Owen Anderson3fe002d2010-09-08 22:16:17 +0000407};
408
Sanjay Patel77bf6222017-04-03 16:53:12 +0000409/// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
410/// satisfies.
411static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
412 ICmpInst::Predicate Pred) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000413 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
414 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
415 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000416 bool IsEq = (Pred == ICmpInst::ICMP_EQ);
417 bool IsAPow2 = (ACst && !ACst->isZero() && ACst->getValue().isPowerOf2());
418 bool IsBPow2 = (BCst && !BCst->isZero() && BCst->getValue().isPowerOf2());
419 unsigned MaskVal = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000420 if (CCst && CCst->isZero()) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000421 // if C is zero, then both A and B qualify as mask
Sanjay Patel77bf6222017-04-03 16:53:12 +0000422 MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
423 : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
424 if (IsAPow2)
425 MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
426 : (AMask_AllOnes | AMask_Mixed));
427 if (IsBPow2)
428 MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
429 : (BMask_AllOnes | BMask_Mixed));
430 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000431 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000432
Owen Anderson3fe002d2010-09-08 22:16:17 +0000433 if (A == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000434 MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
435 : (AMask_NotAllOnes | AMask_NotMixed));
436 if (IsAPow2)
437 MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
438 : (Mask_AllZeros | AMask_Mixed));
439 } else if (ACst && CCst && ConstantExpr::getAnd(ACst, CCst) == CCst) {
440 MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000441 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000442
Craig Topperae48cb22012-12-20 07:15:54 +0000443 if (B == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000444 MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
445 : (BMask_NotAllOnes | BMask_NotMixed));
446 if (IsBPow2)
447 MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
448 : (Mask_AllZeros | BMask_Mixed));
449 } else if (BCst && CCst && ConstantExpr::getAnd(BCst, CCst) == CCst) {
450 MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000451 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000452
453 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000454}
455
Tim Northoverc0756c42013-09-04 11:57:13 +0000456/// Convert an analysis of a masked ICmp into its equivalent if all boolean
457/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
458/// is adjacent to the corresponding normal flag (recording ==), this just
459/// involves swapping those bits over.
460static unsigned conjugateICmpMask(unsigned Mask) {
461 unsigned NewMask;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000462 NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
463 AMask_Mixed | BMask_Mixed))
Tim Northoverc0756c42013-09-04 11:57:13 +0000464 << 1;
465
Sanjay Patel77bf6222017-04-03 16:53:12 +0000466 NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
467 AMask_NotMixed | BMask_NotMixed))
468 >> 1;
Tim Northoverc0756c42013-09-04 11:57:13 +0000469
470 return NewMask;
471}
472
Sanjay Patel77bf6222017-04-03 16:53:12 +0000473/// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
474/// Return the set of pattern classes (from MaskedICmpType) that both LHS and
475/// RHS satisfy.
476static unsigned getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C,
477 Value *&D, Value *&E, ICmpInst *LHS,
478 ICmpInst *RHS,
479 ICmpInst::Predicate &PredL,
480 ICmpInst::Predicate &PredR) {
481 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
482 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000483 // vectors are not (yet?) supported
Sanjay Patel77bf6222017-04-03 16:53:12 +0000484 if (LHS->getOperand(0)->getType()->isVectorTy())
485 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000486
487 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000488 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000489 // and L11 & L12 == L21 & L22. The same goes for RHS.
490 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000491 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000492 // above.
493 Value *L1 = LHS->getOperand(0);
494 Value *L2 = LHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000495 Value *L11, *L12, *L21, *L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000496 // Check whether the icmp can be decomposed into a bit test.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000497 if (decomposeBitTestICmp(LHS, PredL, L11, L12, L2)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000498 L21 = L22 = L1 = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000499 } else {
500 // Look for ANDs in the LHS icmp.
Tim Northoverdc647a22013-09-04 11:57:17 +0000501 if (!L1->getType()->isIntegerTy()) {
502 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000503 L11 = L12 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000504 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
505 // Any icmp can be viewed as being trivially masked; if it allows us to
506 // remove one, it's worth it.
507 L11 = L1;
508 L12 = Constant::getAllOnesValue(L1->getType());
509 }
510
511 if (!L2->getType()->isIntegerTy()) {
512 // You can icmp pointers, for example. They really aren't masks.
Craig Topperf40110f2014-04-25 05:29:35 +0000513 L21 = L22 = nullptr;
Tim Northoverdc647a22013-09-04 11:57:17 +0000514 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
515 L21 = L2;
516 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000517 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000518 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000519
520 // Bail if LHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000521 if (!ICmpInst::isEquality(PredL))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000522 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000523
524 Value *R1 = RHS->getOperand(0);
525 Value *R2 = RHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000526 Value *R11, *R12;
527 bool Ok = false;
528 if (decomposeBitTestICmp(RHS, PredR, R11, R12, R2)) {
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000529 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000530 A = R11;
531 D = R12;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000532 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000533 A = R12;
534 D = R11;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000535 } else {
536 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000537 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000538 E = R2;
539 R1 = nullptr;
540 Ok = true;
Tim Northoverdc647a22013-09-04 11:57:17 +0000541 } else if (R1->getType()->isIntegerTy()) {
542 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
543 // As before, model no mask as a trivial mask if it'll let us do an
Mayur Pandey75b76c62014-08-19 06:41:55 +0000544 // optimization.
Tim Northoverdc647a22013-09-04 11:57:17 +0000545 R11 = R1;
546 R12 = Constant::getAllOnesValue(R1->getType());
547 }
548
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000549 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000550 A = R11;
551 D = R12;
552 E = R2;
553 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000554 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000555 A = R12;
556 D = R11;
557 E = R2;
558 Ok = true;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000559 }
560 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000561
562 // Bail if RHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000563 if (!ICmpInst::isEquality(PredR))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000564 return 0;
565
Chad Rosier58919cc2016-05-09 21:37:43 +0000566 // Look for ANDs on the right side of the RHS icmp.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000567 if (!Ok && R2->getType()->isIntegerTy()) {
Tim Northoverdc647a22013-09-04 11:57:17 +0000568 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
569 R11 = R2;
570 R12 = Constant::getAllOnesValue(R2->getType());
571 }
572
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000573 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000574 A = R11;
575 D = R12;
576 E = R1;
577 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000578 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000579 A = R12;
580 D = R11;
581 E = R1;
582 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000583 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000584 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000585 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000586 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000587 if (!Ok)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000588 return 0;
589
590 if (L11 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000591 B = L12;
592 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000593 } else if (L12 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000594 B = L11;
595 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000596 } else if (L21 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000597 B = L22;
598 C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000599 } else if (L22 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000600 B = L21;
601 C = L1;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000602 }
603
Sanjay Patel77bf6222017-04-03 16:53:12 +0000604 unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
605 unsigned RightType = getMaskedICmpType(A, D, E, PredR);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000606 return LeftType & RightType;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000607}
Sanjay Patel18549272015-09-08 18:24:36 +0000608
609/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
610/// into a single (icmp(A & X) ==/!= Y).
David Majnemer1a3327b2014-11-18 09:31:36 +0000611static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
612 llvm::InstCombiner::BuilderTy *Builder) {
Craig Topperf40110f2014-04-25 05:29:35 +0000613 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000614 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
615 unsigned Mask =
616 getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
617 if (Mask == 0)
618 return nullptr;
619
620 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
621 "Expected equality predicates for masked type of icmps.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000622
Tim Northoverc0756c42013-09-04 11:57:13 +0000623 // In full generality:
624 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
625 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
626 //
627 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
628 // equivalent to (icmp (A & X) !Op Y).
629 //
630 // Therefore, we can pretend for the rest of this function that we're dealing
631 // with the conjunction, provided we flip the sense of any comparisons (both
632 // input and output).
633
634 // In most cases we're going to produce an EQ for the "&&" case.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000635 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Tim Northoverc0756c42013-09-04 11:57:13 +0000636 if (!IsAnd) {
637 // Convert the masking analysis into its equivalent with negated
638 // comparisons.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000639 Mask = conjugateICmpMask(Mask);
Tim Northoverc0756c42013-09-04 11:57:13 +0000640 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000641
Sanjay Patel77bf6222017-04-03 16:53:12 +0000642 if (Mask & Mask_AllZeros) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000643 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000644 // -> (icmp eq (A & (B|D)), 0)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000645 Value *NewOr = Builder->CreateOr(B, D);
646 Value *NewAnd = Builder->CreateAnd(A, NewOr);
647 // We can't use C as zero because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000648 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000649 // with B and D, having a single bit set.
650 Value *Zero = Constant::getNullValue(A->getType());
651 return Builder->CreateICmp(NewCC, NewAnd, Zero);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000652 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000653 if (Mask & BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000654 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000655 // -> (icmp eq (A & (B|D)), (B|D))
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000656 Value *NewOr = Builder->CreateOr(B, D);
657 Value *NewAnd = Builder->CreateAnd(A, NewOr);
658 return Builder->CreateICmp(NewCC, NewAnd, NewOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000659 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000660 if (Mask & AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000661 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000662 // -> (icmp eq (A & (B&D)), A)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000663 Value *NewAnd1 = Builder->CreateAnd(B, D);
664 Value *NewAnd2 = Builder->CreateAnd(A, NewAnd1);
665 return Builder->CreateICmp(NewCC, NewAnd2, A);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000666 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000667
668 // Remaining cases assume at least that B and D are constant, and depend on
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000669 // their actual values. This isn't strictly necessary, just a "handle the
Tim Northoverc0756c42013-09-04 11:57:13 +0000670 // easy cases for now" decision.
671 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000672 if (!BCst)
673 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000674 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000675 if (!DCst)
676 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000677
Sanjay Patel77bf6222017-04-03 16:53:12 +0000678 if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000679 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
680 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
681 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
682 // Only valid if one of the masks is a superset of the other (check "B&D" is
683 // the same as either B or D).
684 APInt NewMask = BCst->getValue() & DCst->getValue();
685
686 if (NewMask == BCst->getValue())
687 return LHS;
688 else if (NewMask == DCst->getValue())
689 return RHS;
690 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000691
692 if (Mask & AMask_NotAllOnes) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000693 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
694 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
695 // Only valid if one of the masks is a superset of the other (check "B|D" is
696 // the same as either B or D).
697 APInt NewMask = BCst->getValue() | DCst->getValue();
698
699 if (NewMask == BCst->getValue())
700 return LHS;
701 else if (NewMask == DCst->getValue())
702 return RHS;
703 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000704
705 if (Mask & BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000706 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000707 // We already know that B & C == C && D & E == E.
708 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
709 // C and E, which are shared by both the mask B and the mask D, don't
710 // contradict, then we can transform to
711 // -> (icmp eq (A & (B|D)), (C|E))
712 // Currently, we only handle the case of B, C, D, and E being constant.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000713 // We can't simply use C and E because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000714 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000715 // with B and D, having a single bit set.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000716 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000717 if (!CCst)
718 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000719 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000720 if (!ECst)
721 return nullptr;
722 if (PredL != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000723 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000724 if (PredR != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000725 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000726
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000727 // If there is a conflict, we should actually return a false for the
728 // whole construct.
David Majnemer1a3327b2014-11-18 09:31:36 +0000729 if (((BCst->getValue() & DCst->getValue()) &
730 (CCst->getValue() ^ ECst->getValue())) != 0)
David Majnemer6fdb6b82014-11-18 09:31:41 +0000731 return ConstantInt::get(LHS->getType(), !IsAnd);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000732
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000733 Value *NewOr1 = Builder->CreateOr(B, D);
734 Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
735 Value *NewAnd = Builder->CreateAnd(A, NewOr1);
736 return Builder->CreateICmp(NewCC, NewAnd, NewOr2);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000737 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000738
Craig Topperf40110f2014-04-25 05:29:35 +0000739 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000740}
741
Erik Ecksteind1817522014-12-03 10:39:15 +0000742/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
743/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
744/// If \p Inverted is true then the check is for the inverted range, e.g.
745/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
746Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
747 bool Inverted) {
748 // Check the lower range comparison, e.g. x >= 0
749 // InstCombine already ensured that if there is a constant it's on the RHS.
750 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
751 if (!RangeStart)
752 return nullptr;
753
754 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
755 Cmp0->getPredicate());
756
757 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
758 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
759 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
760 return nullptr;
761
762 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
763 Cmp1->getPredicate());
764
765 Value *Input = Cmp0->getOperand(0);
766 Value *RangeEnd;
767 if (Cmp1->getOperand(0) == Input) {
768 // For the upper range compare we have: icmp x, n
769 RangeEnd = Cmp1->getOperand(1);
770 } else if (Cmp1->getOperand(1) == Input) {
771 // For the upper range compare we have: icmp n, x
772 RangeEnd = Cmp1->getOperand(0);
773 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
774 } else {
775 return nullptr;
776 }
777
778 // Check the upper range comparison, e.g. x < n
779 ICmpInst::Predicate NewPred;
780 switch (Pred1) {
781 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
782 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
783 default: return nullptr;
784 }
785
786 // This simplification is only valid if the upper range is not negative.
787 bool IsNegative, IsNotNegative;
David Majnemer54c2ca22014-12-26 09:10:14 +0000788 ComputeSignBit(RangeEnd, IsNotNegative, IsNegative, /*Depth=*/0, Cmp1);
Erik Ecksteind1817522014-12-03 10:39:15 +0000789 if (!IsNotNegative)
790 return nullptr;
791
792 if (Inverted)
793 NewPred = ICmpInst::getInversePredicate(NewPred);
794
795 return Builder->CreateICmp(NewPred, Input, RangeEnd);
796}
797
Sanjay Patel18549272015-09-08 18:24:36 +0000798/// Fold (icmp)&(icmp) if possible.
Chris Lattner067459c2010-03-05 08:46:26 +0000799Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000800 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
801
802 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
803 if (PredicatesFoldable(LHSCC, RHSCC)) {
804 if (LHS->getOperand(0) == RHS->getOperand(1) &&
805 LHS->getOperand(1) == RHS->getOperand(0))
806 LHS->swapOperands();
807 if (LHS->getOperand(0) == RHS->getOperand(0) &&
808 LHS->getOperand(1) == RHS->getOperand(1)) {
809 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
810 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
811 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000812 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000813 }
814 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000815
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000816 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000817 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000818 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000819
Erik Ecksteind1817522014-12-03 10:39:15 +0000820 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
821 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
822 return V;
823
824 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
825 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
826 return V;
827
Chris Lattner0a8191e2010-01-05 07:50:36 +0000828 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
829 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
830 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
831 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +0000832 if (!LHSCst || !RHSCst) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000833
Chris Lattner0a8191e2010-01-05 07:50:36 +0000834 if (LHSCst == RHSCst && LHSCC == RHSCC) {
835 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000836 // where C is a power of 2 or
Chris Lattner0a8191e2010-01-05 07:50:36 +0000837 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000838 if ((LHSCC == ICmpInst::ICMP_ULT && LHSCst->getValue().isPowerOf2()) ||
839 (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000840 Value *NewOr = Builder->CreateOr(Val, Val2);
Chris Lattner067459c2010-03-05 08:46:26 +0000841 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000842 }
843 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000844
Benjamin Kramer101720f2011-04-28 20:09:57 +0000845 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000846 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000847 // iff the lower bits of C2 and CA are zero.
Bill Wendlingf2c78f32012-02-29 01:46:50 +0000848 if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000849 LHS->hasOneUse() && RHS->hasOneUse()) {
850 Value *V;
Craig Topperf40110f2014-04-25 05:29:35 +0000851 ConstantInt *AndCst, *SmallCst = nullptr, *BigCst = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000852
853 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000854 // (and x, CA) == C2 & (trunc x) == C1
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000855 if (match(Val2, m_Trunc(m_Value(V))) &&
856 match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
857 SmallCst = RHSCst;
858 BigCst = LHSCst;
Craig Topperae48cb22012-12-20 07:15:54 +0000859 } else if (match(Val, m_Trunc(m_Value(V))) &&
860 match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000861 SmallCst = LHSCst;
862 BigCst = RHSCst;
863 }
864
865 if (SmallCst && BigCst) {
866 unsigned BigBitSize = BigCst->getType()->getBitWidth();
867 unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
868
869 // Check that the low bits are zero.
870 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Benjamin Kramercf9d1ad2011-04-28 21:38:51 +0000871 if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000872 Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
873 APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
874 Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
875 return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
876 }
877 }
878 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000879
Chris Lattner0a8191e2010-01-05 07:50:36 +0000880 // From here on, we only handle:
881 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Craig Topperf40110f2014-04-25 05:29:35 +0000882 if (Val != Val2) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000883
Chris Lattner0a8191e2010-01-05 07:50:36 +0000884 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
885 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
886 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
887 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
888 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000889 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000890
Chris Lattner0a8191e2010-01-05 07:50:36 +0000891 // We can't fold (ugt x, C) & (sgt x, C2).
892 if (!PredicatesFoldable(LHSCC, RHSCC))
Craig Topperf40110f2014-04-25 05:29:35 +0000893 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000894
Chris Lattner0a8191e2010-01-05 07:50:36 +0000895 // Ensure that the larger constant is on the RHS.
896 bool ShouldSwap;
897 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +0000898 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000899 CmpInst::isSigned(RHSCC)))
900 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
901 else
902 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000903
Chris Lattner0a8191e2010-01-05 07:50:36 +0000904 if (ShouldSwap) {
905 std::swap(LHS, RHS);
906 std::swap(LHSCst, RHSCst);
907 std::swap(LHSCC, RHSCC);
908 }
909
Dan Gohman4a618822010-02-10 16:03:48 +0000910 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000911 // comparing a value against two constants and and'ing the result
912 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +0000913 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
914 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +0000915 // are not equal and that the larger constant is on the RHS
916 assert(LHSCst != RHSCst && "Compares not folded above?");
917
918 switch (LHSCC) {
919 default: llvm_unreachable("Unknown integer condition code!");
920 case ICmpInst::ICMP_EQ:
921 switch (RHSCC) {
922 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000923 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
924 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
925 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner067459c2010-03-05 08:46:26 +0000926 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000927 }
928 case ICmpInst::ICMP_NE:
929 switch (RHSCC) {
930 default: llvm_unreachable("Unknown integer condition code!");
931 case ICmpInst::ICMP_ULT:
932 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000933 return Builder->CreateICmpULT(Val, LHSCst);
Benjamin Kramer240b85e2014-10-12 14:02:34 +0000934 if (LHSCst->isNullValue()) // (X != 0 & X u< 14) -> X-1 u< 13
Sanjay Patel85d79742016-08-31 19:49:56 +0000935 return insertRangeTest(Val, LHSCst->getValue() + 1, RHSCst->getValue(),
936 false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000937 break; // (X != 13 & X u< 15) -> no change
938 case ICmpInst::ICMP_SLT:
939 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000940 return Builder->CreateICmpSLT(Val, LHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000941 break; // (X != 13 & X s< 15) -> no change
942 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
943 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
944 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000945 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000946 case ICmpInst::ICMP_NE:
Jim Grosbach20e3b9a2013-08-16 00:15:20 +0000947 // Special case to get the ordering right when the values wrap around
948 // zero.
Jim Grosbachd0de8ac2013-08-16 17:03:36 +0000949 if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
Jim Grosbach20e3b9a2013-08-16 00:15:20 +0000950 std::swap(LHSCst, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000951 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
952 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
953 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Jim Grosbach20e3b9a2013-08-16 00:15:20 +0000954 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
955 Val->getName()+".cmp");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000956 }
957 break; // (X != 13 & X != 15) -> no change
958 }
959 break;
960 case ICmpInst::ICMP_ULT:
961 switch (RHSCC) {
962 default: llvm_unreachable("Unknown integer condition code!");
963 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
964 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner067459c2010-03-05 08:46:26 +0000965 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000966 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
967 break;
968 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
969 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner067459c2010-03-05 08:46:26 +0000970 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000971 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
972 break;
973 }
974 break;
975 case ICmpInst::ICMP_SLT:
976 switch (RHSCC) {
977 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000978 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
979 break;
980 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
981 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner067459c2010-03-05 08:46:26 +0000982 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000983 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
984 break;
985 }
986 break;
987 case ICmpInst::ICMP_UGT:
988 switch (RHSCC) {
989 default: llvm_unreachable("Unknown integer condition code!");
990 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
991 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
Chris Lattner067459c2010-03-05 08:46:26 +0000992 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000993 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
994 break;
995 case ICmpInst::ICMP_NE:
996 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Chris Lattner067459c2010-03-05 08:46:26 +0000997 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000998 break; // (X u> 13 & X != 15) -> no change
999 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Sanjay Patel85d79742016-08-31 19:49:56 +00001000 return insertRangeTest(Val, LHSCst->getValue() + 1, RHSCst->getValue(),
1001 false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001002 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
1003 break;
1004 }
1005 break;
1006 case ICmpInst::ICMP_SGT:
1007 switch (RHSCC) {
1008 default: llvm_unreachable("Unknown integer condition code!");
1009 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1010 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
Chris Lattner067459c2010-03-05 08:46:26 +00001011 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001012 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1013 break;
1014 case ICmpInst::ICMP_NE:
1015 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Chris Lattner067459c2010-03-05 08:46:26 +00001016 return Builder->CreateICmp(LHSCC, Val, RHSCst);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001017 break; // (X s> 13 & X != 15) -> no change
1018 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Sanjay Patel85d79742016-08-31 19:49:56 +00001019 return insertRangeTest(Val, LHSCst->getValue() + 1, RHSCst->getValue(),
1020 true, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001021 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1022 break;
1023 }
1024 break;
1025 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001026
Craig Topperf40110f2014-04-25 05:29:35 +00001027 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001028}
1029
Sanjay Patel18549272015-09-08 18:24:36 +00001030/// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
1031/// a Value which should already be inserted into the function.
Chris Lattner067459c2010-03-05 08:46:26 +00001032Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +00001033 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1034 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1035 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1036
1037 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1038 // Swap RHS operands to match LHS.
1039 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1040 std::swap(Op1LHS, Op1RHS);
1041 }
1042
1043 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1044 // Suppose the relation between x and y is R, where R is one of
1045 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
1046 // testing the desired relations.
1047 //
1048 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1049 // bool(R & CC0) && bool(R & CC1)
1050 // = bool((R & CC0) & (R & CC1))
1051 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
1052 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1053 return getFCmpValue(getFCmpCode(Op0CC) & getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1054 Builder);
1055
Chris Lattner0a8191e2010-01-05 07:50:36 +00001056 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1057 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +00001058 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001059 return nullptr;
Benjamin Kramere89c7052013-04-12 21:56:23 +00001060
Chris Lattner0a8191e2010-01-05 07:50:36 +00001061 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1062 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1063 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1064 // If either of the constants are nans, then the whole thing returns
1065 // false.
1066 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001067 return Builder->getFalse();
Chris Lattner067459c2010-03-05 08:46:26 +00001068 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001069 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001070
Chris Lattner0a8191e2010-01-05 07:50:36 +00001071 // Handle vector zeros. This occurs because the canonical form of
1072 // "fcmp ord x,x" is "fcmp ord x, 0".
1073 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1074 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001075 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Craig Topperf40110f2014-04-25 05:29:35 +00001076 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001077 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001078
Craig Topperf40110f2014-04-25 05:29:35 +00001079 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001080}
1081
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001082/// Match De Morgan's Laws:
1083/// (~A & ~B) == (~(A | B))
1084/// (~A | ~B) == (~(A & B))
1085static Instruction *matchDeMorgansLaws(BinaryOperator &I,
1086 InstCombiner::BuilderTy *Builder) {
1087 auto Opcode = I.getOpcode();
1088 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1089 "Trying to match De Morgan's Laws with something other than and/or");
Sanjay Patele1b09ca2015-09-25 23:21:38 +00001090 // Flip the logic operation.
1091 if (Opcode == Instruction::And)
1092 Opcode = Instruction::Or;
1093 else
1094 Opcode = Instruction::And;
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001095
1096 Value *Op0 = I.getOperand(0);
1097 Value *Op1 = I.getOperand(1);
1098 // TODO: Use pattern matchers instead of dyn_cast.
1099 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1100 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1101 if (Op0->hasOneUse() && Op1->hasOneUse()) {
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001102 Value *LogicOp = Builder->CreateBinOp(Opcode, Op0NotVal, Op1NotVal,
1103 I.getName() + ".demorgan");
1104 return BinaryOperator::CreateNot(LogicOp);
1105 }
1106
1107 return nullptr;
1108}
1109
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001110bool InstCombiner::shouldOptimizeCast(CastInst *CI) {
1111 Value *CastSrc = CI->getOperand(0);
1112
1113 // Noop casts and casts of constants should be eliminated trivially.
1114 if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
1115 return false;
1116
1117 // If this cast is paired with another cast that can be eliminated, we prefer
1118 // to have it eliminated.
1119 if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
1120 if (isEliminableCastPair(PrecedingCI, CI))
1121 return false;
1122
1123 // If this is a vector sext from a compare, then we don't want to break the
1124 // idiom where each element of the extended vector is either zero or all ones.
1125 if (CI->getOpcode() == Instruction::SExt &&
1126 isa<CmpInst>(CastSrc) && CI->getDestTy()->isVectorTy())
1127 return false;
1128
1129 return true;
1130}
1131
Sanjay Patel60312bc42016-09-12 00:16:23 +00001132/// Fold {and,or,xor} (cast X), C.
1133static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
1134 InstCombiner::BuilderTy *Builder) {
1135 Constant *C;
1136 if (!match(Logic.getOperand(1), m_Constant(C)))
1137 return nullptr;
1138
1139 auto LogicOpc = Logic.getOpcode();
1140 Type *DestTy = Logic.getType();
1141 Type *SrcTy = Cast->getSrcTy();
1142
1143 // If the first operand is bitcast, move the logic operation ahead of the
1144 // bitcast (do the logic operation in the original type). This can eliminate
1145 // bitcasts and allow combines that would otherwise be impeded by the bitcast.
1146 Value *X;
1147 if (match(Cast, m_BitCast(m_Value(X)))) {
1148 Value *NewConstant = ConstantExpr::getBitCast(C, SrcTy);
1149 Value *NewOp = Builder->CreateBinOp(LogicOpc, X, NewConstant);
1150 return CastInst::CreateBitOrPointerCast(NewOp, DestTy);
1151 }
1152
1153 // Similarly, move the logic operation ahead of a zext if the constant is
1154 // unchanged in the smaller source type. Performing the logic in a smaller
1155 // type may provide more information to later folds, and the smaller logic
1156 // instruction may be cheaper (particularly in the case of vectors).
1157 if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1158 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1159 Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1160 if (ZextTruncC == C) {
1161 // LogicOpc (zext X), C --> zext (LogicOpc X, C)
1162 Value *NewOp = Builder->CreateBinOp(LogicOpc, X, TruncC);
1163 return new ZExtInst(NewOp, DestTy);
1164 }
1165 }
1166
1167 return nullptr;
1168}
1169
1170/// Fold {and,or,xor} (cast X), Y.
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001171Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001172 auto LogicOpc = I.getOpcode();
Sanjay Patel1e6ca442016-11-22 22:54:36 +00001173 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001174
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001175 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001176 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
Sanjay Patel9bba7502016-03-03 19:19:04 +00001177 if (!Cast0)
Sanjay Patel7d0d8102016-02-23 16:59:21 +00001178 return nullptr;
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001179
Sanjay Patel9bba7502016-03-03 19:19:04 +00001180 // This must be a cast from an integer or integer vector source type to allow
1181 // transformation of the logic operation to the source type.
1182 Type *DestTy = I.getType();
Sanjay Patel713f25e2016-02-23 17:41:34 +00001183 Type *SrcTy = Cast0->getSrcTy();
Sanjay Patel9bba7502016-03-03 19:19:04 +00001184 if (!SrcTy->isIntOrIntVectorTy())
1185 return nullptr;
1186
Sanjay Patel60312bc42016-09-12 00:16:23 +00001187 if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1188 return Ret;
Sanjay Patel0753c062016-07-21 00:24:18 +00001189
Sanjay Patel9bba7502016-03-03 19:19:04 +00001190 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1191 if (!Cast1)
1192 return nullptr;
1193
1194 // Both operands of the logic operation are casts. The casts must be of the
1195 // same type for reduction.
1196 auto CastOpcode = Cast0->getOpcode();
1197 if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
Sanjay Patel713f25e2016-02-23 17:41:34 +00001198 return nullptr;
1199
1200 Value *Cast0Src = Cast0->getOperand(0);
1201 Value *Cast1Src = Cast1->getOperand(0);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001202
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001203 // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
Tobias Grosser8757e382016-08-03 19:30:35 +00001204 if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001205 Value *NewOp = Builder->CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
1206 I.getName());
Sanjay Patel713f25e2016-02-23 17:41:34 +00001207 return CastInst::Create(CastOpcode, NewOp, DestTy);
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001208 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001209
Sanjay Pateldbbaca02016-02-24 17:00:34 +00001210 // For now, only 'and'/'or' have optimizations after this.
1211 if (LogicOpc == Instruction::Xor)
1212 return nullptr;
1213
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001214 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001215 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001216 ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1217 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1218 if (ICmp0 && ICmp1) {
1219 Value *Res = LogicOpc == Instruction::And ? FoldAndOfICmps(ICmp0, ICmp1)
1220 : FoldOrOfICmps(ICmp0, ICmp1, &I);
1221 if (Res)
1222 return CastInst::Create(CastOpcode, Res, DestTy);
1223 return nullptr;
1224 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001225
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001226 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001227 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001228 FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1229 FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1230 if (FCmp0 && FCmp1) {
1231 Value *Res = LogicOpc == Instruction::And ? FoldAndOfFCmps(FCmp0, FCmp1)
1232 : FoldOrOfFCmps(FCmp0, FCmp1);
1233 if (Res)
1234 return CastInst::Create(CastOpcode, Res, DestTy);
1235 return nullptr;
1236 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001237
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001238 return nullptr;
1239}
1240
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001241static Instruction *foldBoolSextMaskToSelect(BinaryOperator &I) {
1242 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1243
1244 // Canonicalize SExt or Not to the LHS
1245 if (match(Op1, m_SExt(m_Value())) || match(Op1, m_Not(m_Value()))) {
1246 std::swap(Op0, Op1);
1247 }
1248
1249 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1250 Value *X = nullptr;
1251 if (match(Op0, m_SExt(m_Value(X))) &&
1252 X->getType()->getScalarType()->isIntegerTy(1)) {
1253 Value *Zero = Constant::getNullValue(Op1->getType());
1254 return SelectInst::Create(X, Op1, Zero);
1255 }
1256
1257 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1258 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1259 X->getType()->getScalarType()->isIntegerTy(1)) {
1260 Value *Zero = Constant::getNullValue(Op0->getType());
1261 return SelectInst::Create(X, Zero, Op1);
1262 }
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001263
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001264 return nullptr;
1265}
1266
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001267// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1268// here. We should standardize that construct where it is needed or choose some
1269// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001270Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001271 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001272 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1273
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001274 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001275 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001276
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001277 if (Value *V = SimplifyAndInst(Op0, Op1, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001278 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001279
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001280 // (A|B)&(A|C) -> A|(B&C) etc
1281 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001282 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00001283
Craig Topper9d4171a2012-12-20 07:09:41 +00001284 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001285 // purpose is to compute bits we don't care about.
1286 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001287 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001288
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001289 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001290 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001291
Chris Lattner0a8191e2010-01-05 07:50:36 +00001292 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1293 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001294
1295 // Optimize a variety of ((val OP C1) & C2) combinations...
1296 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1297 Value *Op0LHS = Op0I->getOperand(0);
1298 Value *Op0RHS = Op0I->getOperand(1);
1299 switch (Op0I->getOpcode()) {
1300 default: break;
1301 case Instruction::Xor:
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001302 case Instruction::Or: {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001303 // If the mask is only needed on one incoming arm, push it up.
1304 if (!Op0I->hasOneUse()) break;
Craig Topper9d4171a2012-12-20 07:09:41 +00001305
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001306 APInt NotAndRHS(~AndRHSMask);
Hal Finkel60db0582014-09-07 18:57:58 +00001307 if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001308 // Not masking anything out for the LHS, move to RHS.
1309 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1310 Op0RHS->getName()+".masked");
1311 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1312 }
1313 if (!isa<Constant>(Op0RHS) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001314 MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001315 // Not masking anything out for the RHS, move to LHS.
1316 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1317 Op0LHS->getName()+".masked");
1318 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1319 }
1320
1321 break;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001322 }
Craig Topper79120e82017-04-03 17:22:23 +00001323 case Instruction::Add:
1324 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1325 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1326 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1327 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1328 return BinaryOperator::CreateAnd(V, AndRHS);
1329 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1330 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1331 break;
1332
Chris Lattner0a8191e2010-01-05 07:50:36 +00001333 case Instruction::Sub:
Craig Topper79120e82017-04-03 17:22:23 +00001334 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1335 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1336 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1337 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1338 return BinaryOperator::CreateAnd(V, AndRHS);
1339
Balaram Makamccf59732015-08-20 15:35:00 +00001340 // -x & 1 -> x & 1
1341 if (AndRHSMask == 1 && match(Op0LHS, m_Zero()))
1342 return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
1343
Chris Lattner0a8191e2010-01-05 07:50:36 +00001344 break;
1345
1346 case Instruction::Shl:
1347 case Instruction::LShr:
1348 // (1 << x) & 1 --> zext(x == 0)
1349 // (1 >> x) & 1 --> zext(x == 0)
1350 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1351 Value *NewICmp =
1352 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1353 return new ZExtInst(NewICmp, I.getType());
1354 }
1355 break;
1356 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001357
David Majnemerde55c602017-01-17 18:08:06 +00001358 // ((C1 OP zext(X)) & C2) -> zext((C1-X) & C2) if C2 fits in the bitwidth
1359 // of X and OP behaves well when given trunc(C1) and X.
1360 switch (Op0I->getOpcode()) {
1361 default:
1362 break;
1363 case Instruction::Xor:
1364 case Instruction::Or:
1365 case Instruction::Mul:
1366 case Instruction::Add:
1367 case Instruction::Sub:
1368 Value *X;
1369 ConstantInt *C1;
1370 if (match(Op0I, m_BinOp(m_ZExt(m_Value(X)), m_ConstantInt(C1))) ||
1371 match(Op0I, m_BinOp(m_ConstantInt(C1), m_ZExt(m_Value(X))))) {
1372 if (AndRHSMask.isIntN(X->getType()->getScalarSizeInBits())) {
1373 auto *TruncC1 = ConstantExpr::getTrunc(C1, X->getType());
1374 Value *BinOp;
1375 if (isa<ZExtInst>(Op0LHS))
1376 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), X, TruncC1);
1377 else
1378 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), TruncC1, X);
1379 auto *TruncC2 = ConstantExpr::getTrunc(AndRHS, X->getType());
1380 auto *And = Builder->CreateAnd(BinOp, TruncC2);
1381 return new ZExtInst(And, I.getType());
1382 }
1383 }
1384 }
1385
Chris Lattner0a8191e2010-01-05 07:50:36 +00001386 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1387 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1388 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001389 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001390
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001391 // If this is an integer truncation, and if the source is an 'and' with
1392 // immediate, transform it. This frequently occurs for bitfield accesses.
1393 {
Craig Topperf40110f2014-04-25 05:29:35 +00001394 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001395 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1396 // Change: and (trunc (and X, YC) to T), C2
1397 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001398 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001399 // other simplifications.
1400 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1401 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1402 C3 = ConstantExpr::getAnd(C3, AndRHS);
1403 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001404 }
1405 }
1406
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001407 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1408 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001409 }
1410
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001411 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
1412 return DeMorgan;
Craig Topper9d4171a2012-12-20 07:09:41 +00001413
Chris Lattner0a8191e2010-01-05 07:50:36 +00001414 {
Craig Topperf40110f2014-04-25 05:29:35 +00001415 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001416 // (A|B) & ~(A&B) -> A^B
1417 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1418 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1419 ((A == C && B == D) || (A == D && B == C)))
1420 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001421
Chris Lattner0a8191e2010-01-05 07:50:36 +00001422 // ~(A&B) & (A|B) -> A^B
1423 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1424 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1425 ((A == C && B == D) || (A == D && B == C)))
1426 return BinaryOperator::CreateXor(A, B);
Craig Topper9d4171a2012-12-20 07:09:41 +00001427
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001428 // A&(A^B) => A & ~B
1429 {
1430 Value *tmpOp0 = Op0;
1431 Value *tmpOp1 = Op1;
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001432 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001433 if (A == Op1 || B == Op1 ) {
1434 tmpOp1 = Op0;
1435 tmpOp0 = Op1;
1436 // Simplify below
1437 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001438 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001439
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001440 if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001441 if (B == tmpOp0) {
1442 std::swap(A, B);
1443 }
Sanjay Pateld09b44a2016-01-18 17:50:23 +00001444 // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001445 // A is originally -1 (or a vector of -1 and undefs), then we enter
1446 // an endless loop. By checking that A is non-constant we ensure that
1447 // we will never get to the loop.
1448 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001449 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001450 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001451 }
1452
1453 // (A&((~A)|B)) -> A&B
1454 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1455 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1456 return BinaryOperator::CreateAnd(A, Op1);
1457 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1458 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1459 return BinaryOperator::CreateAnd(A, Op0);
David Majnemer42af3602014-07-30 21:26:37 +00001460
1461 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1462 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1463 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
1464 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
1465 return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1466
1467 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1468 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1469 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
1470 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
1471 return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001472
1473 // (A | B) & ((~A) ^ B) -> (A & B)
1474 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1475 match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
1476 return BinaryOperator::CreateAnd(A, B);
1477
1478 // ((~A) ^ B) & (A | B) -> (A & B)
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001479 // ((~A) ^ B) & (B | A) -> (A & B)
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001480 if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001481 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001482 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001483 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001484
David Majnemer5e96f1b2014-08-30 06:18:20 +00001485 {
1486 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1487 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1488 if (LHS && RHS)
Chris Lattner067459c2010-03-05 08:46:26 +00001489 if (Value *Res = FoldAndOfICmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001490 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001491
David Majnemer5e96f1b2014-08-30 06:18:20 +00001492 // TODO: Make this recursive; it's a little tricky because an arbitrary
1493 // number of 'and' instructions might have to be created.
1494 Value *X, *Y;
1495 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1496 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1497 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
Sanjay Patel4b198802016-02-01 22:23:39 +00001498 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001499 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1500 if (Value *Res = FoldAndOfICmps(LHS, Cmp))
Sanjay Patel4b198802016-02-01 22:23:39 +00001501 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001502 }
1503 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1504 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1505 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001506 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001507 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1508 if (Value *Res = FoldAndOfICmps(Cmp, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001509 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001510 }
1511 }
1512
Chris Lattner4e8137d2010-02-11 06:26:33 +00001513 // If and'ing two fcmp, try combine them into one.
1514 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1515 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00001516 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001517 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001518
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001519 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1520 return CastedAnd;
Craig Topper9d4171a2012-12-20 07:09:41 +00001521
Sanjay Patel74d23ad2016-05-27 21:41:29 +00001522 if (Instruction *Select = foldBoolSextMaskToSelect(I))
1523 return Select;
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001524
Craig Topperf40110f2014-04-25 05:29:35 +00001525 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001526}
1527
Chad Rosiera00df492016-05-25 16:22:14 +00001528/// Given an OR instruction, check to see if this is a bswap idiom. If so,
1529/// insert the new intrinsic and return it.
1530Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chad Rosiere5819e22016-05-26 14:58:51 +00001531 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1532
1533 // Look through zero extends.
1534 if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1535 Op0 = Ext->getOperand(0);
1536
1537 if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1538 Op1 = Ext->getOperand(0);
1539
1540 // (A | B) | C and A | (B | C) -> bswap if possible.
1541 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1542 match(Op1, m_Or(m_Value(), m_Value()));
1543
1544 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1545 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1546 match(Op1, m_LogicalShift(m_Value(), m_Value()));
1547
1548 // (A & B) | (C & D) -> bswap if possible.
1549 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1550 match(Op1, m_And(m_Value(), m_Value()));
1551
1552 if (!OrOfOrs && !OrOfShifts && !OrOfAnds)
1553 return nullptr;
1554
James Molloyf01488e2016-01-15 09:20:19 +00001555 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00001556 if (!recognizeBSwapOrBitReverseIdiom(&I, true, false, Insts))
Craig Topperf40110f2014-04-25 05:29:35 +00001557 return nullptr;
James Molloyf01488e2016-01-15 09:20:19 +00001558 Instruction *LastInst = Insts.pop_back_val();
1559 LastInst->removeFromParent();
Craig Topper9d4171a2012-12-20 07:09:41 +00001560
James Molloyf01488e2016-01-15 09:20:19 +00001561 for (auto *Inst : Insts)
1562 Worklist.Add(Inst);
1563 return LastInst;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001564}
1565
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001566/// If all elements of two constant vectors are 0/-1 and inverses, return true.
1567static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
1568 unsigned NumElts = C1->getType()->getVectorNumElements();
1569 for (unsigned i = 0; i != NumElts; ++i) {
1570 Constant *EltC1 = C1->getAggregateElement(i);
1571 Constant *EltC2 = C2->getAggregateElement(i);
1572 if (!EltC1 || !EltC2)
1573 return false;
1574
1575 // One element must be all ones, and the other must be all zeros.
1576 // FIXME: Allow undef elements.
1577 if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
1578 (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
1579 return false;
1580 }
1581 return true;
1582}
1583
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001584/// We have an expression of the form (A & C) | (B & D). If A is a scalar or
1585/// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
1586/// B, it can be used as the condition operand of a select instruction.
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001587static Value *getSelectCondition(Value *A, Value *B,
1588 InstCombiner::BuilderTy &Builder) {
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001589 // If these are scalars or vectors of i1, A can be used directly.
1590 Type *Ty = A->getType();
1591 if (match(A, m_Not(m_Specific(B))) && Ty->getScalarType()->isIntegerTy(1))
1592 return A;
1593
1594 // If A and B are sign-extended, look through the sexts to find the booleans.
1595 Value *Cond;
1596 if (match(A, m_SExt(m_Value(Cond))) &&
1597 Cond->getType()->getScalarType()->isIntegerTy(1) &&
1598 match(B, m_CombineOr(m_Not(m_SExt(m_Specific(Cond))),
1599 m_SExt(m_Not(m_Specific(Cond))))))
1600 return Cond;
1601
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001602 // All scalar (and most vector) possibilities should be handled now.
1603 // Try more matches that only apply to non-splat constant vectors.
1604 if (!Ty->isVectorTy())
1605 return nullptr;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001606
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001607 // If both operands are constants, see if the constants are inverse bitmasks.
1608 Constant *AC, *BC;
1609 if (match(A, m_Constant(AC)) && match(B, m_Constant(BC)) &&
1610 areInverseVectorBitmasks(AC, BC))
1611 return ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1612
1613 // If both operands are xor'd with constants using the same sexted boolean
1614 // operand, see if the constants are inverse bitmasks.
1615 if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AC)))) &&
1616 match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BC)))) &&
1617 Cond->getType()->getScalarType()->isIntegerTy(1) &&
1618 areInverseVectorBitmasks(AC, BC)) {
1619 AC = ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1620 return Builder.CreateXor(Cond, AC);
1621 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001622 return nullptr;
1623}
1624
1625/// We have an expression of the form (A & C) | (B & D). Try to simplify this
1626/// to "A' ? C : D", where A' is a boolean or vector of booleans.
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001627static Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D,
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001628 InstCombiner::BuilderTy &Builder) {
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001629 // The potential condition of the select may be bitcasted. In that case, look
1630 // through its bitcast and the corresponding bitcast of the 'not' condition.
1631 Type *OrigType = A->getType();
1632 Value *SrcA, *SrcB;
Sanjay Patel664514f2016-07-08 21:17:51 +00001633 if (match(A, m_OneUse(m_BitCast(m_Value(SrcA)))) &&
1634 match(B, m_OneUse(m_BitCast(m_Value(SrcB))))) {
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001635 A = SrcA;
1636 B = SrcB;
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001637 }
1638
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001639 if (Value *Cond = getSelectCondition(A, B, Builder)) {
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001640 // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001641 // The bitcasts will either all exist or all not exist. The builder will
1642 // not create unnecessary casts if the types already match.
1643 Value *BitcastC = Builder.CreateBitCast(C, A->getType());
1644 Value *BitcastD = Builder.CreateBitCast(D, A->getType());
1645 Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
1646 return Builder.CreateBitCast(Select, OrigType);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001647 }
Sanjay Patel5c0bc022016-06-02 18:03:05 +00001648
Craig Topperf40110f2014-04-25 05:29:35 +00001649 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001650}
1651
Sanjay Patel18549272015-09-08 18:24:36 +00001652/// Fold (icmp)|(icmp) if possible.
Hal Finkel60db0582014-09-07 18:57:58 +00001653Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
1654 Instruction *CxtI) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001655 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1656
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001657 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1658 // if K1 and K2 are a one-bit mask.
1659 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1660 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1661
1662 if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
1663 RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1664
1665 BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1666 BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1667 if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1668 LAnd->getOpcode() == Instruction::And &&
1669 RAnd->getOpcode() == Instruction::And) {
1670
Craig Topperf40110f2014-04-25 05:29:35 +00001671 Value *Mask = nullptr;
1672 Value *Masked = nullptr;
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001673 if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001674 isKnownToBeAPowerOfTwo(LAnd->getOperand(1), DL, false, 0, &AC, CxtI,
Justin Bogner99798402016-08-05 01:06:44 +00001675 &DT) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001676 isKnownToBeAPowerOfTwo(RAnd->getOperand(1), DL, false, 0, &AC, CxtI,
Justin Bogner99798402016-08-05 01:06:44 +00001677 &DT)) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001678 Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1679 Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1680 } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001681 isKnownToBeAPowerOfTwo(LAnd->getOperand(0), DL, false, 0, &AC,
1682 CxtI, &DT) &&
1683 isKnownToBeAPowerOfTwo(RAnd->getOperand(0), DL, false, 0, &AC,
1684 CxtI, &DT)) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001685 Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1686 Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1687 }
1688
1689 if (Masked)
1690 return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1691 }
1692 }
1693
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001694 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1695 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1696 // The original condition actually refers to the following two ranges:
1697 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1698 // We can fold these two ranges if:
1699 // 1) C1 and C2 is unsigned greater than C3.
1700 // 2) The two ranges are separated.
1701 // 3) C1 ^ C2 is one-bit mask.
1702 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1703 // This implies all values in the two ranges differ by exactly one bit.
1704
1705 if ((LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_ULE) &&
1706 LHSCC == RHSCC && LHSCst && RHSCst && LHS->hasOneUse() &&
1707 RHS->hasOneUse() && LHSCst->getType() == RHSCst->getType() &&
1708 LHSCst->getValue() == (RHSCst->getValue())) {
1709
1710 Value *LAdd = LHS->getOperand(0);
1711 Value *RAdd = RHS->getOperand(0);
1712
1713 Value *LAddOpnd, *RAddOpnd;
1714 ConstantInt *LAddCst, *RAddCst;
1715 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddCst))) &&
1716 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddCst))) &&
1717 LAddCst->getValue().ugt(LHSCst->getValue()) &&
1718 RAddCst->getValue().ugt(LHSCst->getValue())) {
1719
1720 APInt DiffCst = LAddCst->getValue() ^ RAddCst->getValue();
1721 if (LAddOpnd == RAddOpnd && DiffCst.isPowerOf2()) {
1722 ConstantInt *MaxAddCst = nullptr;
1723 if (LAddCst->getValue().ult(RAddCst->getValue()))
1724 MaxAddCst = RAddCst;
1725 else
1726 MaxAddCst = LAddCst;
1727
1728 APInt RRangeLow = -RAddCst->getValue();
1729 APInt RRangeHigh = RRangeLow + LHSCst->getValue();
1730 APInt LRangeLow = -LAddCst->getValue();
1731 APInt LRangeHigh = LRangeLow + LHSCst->getValue();
1732 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1733 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1734 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1735 : RRangeLow - LRangeLow;
1736
1737 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
1738 RangeDiff.ugt(LHSCst->getValue())) {
1739 Value *MaskCst = ConstantInt::get(LAddCst->getType(), ~DiffCst);
1740
1741 Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskCst);
1742 Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddCst);
1743 return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSCst));
1744 }
1745 }
1746 }
1747 }
1748
Chris Lattner0a8191e2010-01-05 07:50:36 +00001749 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1750 if (PredicatesFoldable(LHSCC, RHSCC)) {
1751 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1752 LHS->getOperand(1) == RHS->getOperand(0))
1753 LHS->swapOperands();
1754 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1755 LHS->getOperand(1) == RHS->getOperand(1)) {
1756 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1757 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1758 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001759 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001760 }
1761 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001762
1763 // handle (roughly):
1764 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001765 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001766 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001767
Chris Lattner0a8191e2010-01-05 07:50:36 +00001768 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001769 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1770 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1771 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001772 Value *A = nullptr, *B = nullptr;
David Majnemerc2a990b2013-07-05 00:31:17 +00001773 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
1774 B = Val;
1775 if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
1776 A = Val2;
1777 else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
1778 A = RHS->getOperand(1);
1779 }
1780 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1781 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1782 else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1783 B = Val2;
1784 if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
1785 A = Val;
1786 else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
1787 A = LHS->getOperand(1);
1788 }
1789 if (A && B)
1790 return Builder->CreateICmp(
1791 ICmpInst::ICMP_UGE,
1792 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1793 }
1794
Erik Ecksteind1817522014-12-03 10:39:15 +00001795 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1796 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1797 return V;
1798
1799 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1800 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1801 return V;
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001802
David Majnemerc2a990b2013-07-05 00:31:17 +00001803 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Craig Topperf40110f2014-04-25 05:29:35 +00001804 if (!LHSCst || !RHSCst) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001805
Owen Anderson8f306a72010-08-02 09:32:13 +00001806 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1807 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1808 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1809 Value *NewOr = Builder->CreateOr(Val, Val2);
1810 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1811 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001812 }
1813
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001814 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001815 // iff C2 + CA == C1.
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001816 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001817 ConstantInt *AddCst;
1818 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1819 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001820 return Builder->CreateICmpULE(Val, LHSCst);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001821 }
1822
Chris Lattner0a8191e2010-01-05 07:50:36 +00001823 // From here on, we only handle:
1824 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Craig Topperf40110f2014-04-25 05:29:35 +00001825 if (Val != Val2) return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001826
Chris Lattner0a8191e2010-01-05 07:50:36 +00001827 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1828 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1829 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1830 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1831 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001832 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001833
Chris Lattner0a8191e2010-01-05 07:50:36 +00001834 // We can't fold (ugt x, C) | (sgt x, C2).
1835 if (!PredicatesFoldable(LHSCC, RHSCC))
Craig Topperf40110f2014-04-25 05:29:35 +00001836 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001837
Chris Lattner0a8191e2010-01-05 07:50:36 +00001838 // Ensure that the larger constant is on the RHS.
1839 bool ShouldSwap;
1840 if (CmpInst::isSigned(LHSCC) ||
Craig Topper9d4171a2012-12-20 07:09:41 +00001841 (ICmpInst::isEquality(LHSCC) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00001842 CmpInst::isSigned(RHSCC)))
1843 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1844 else
1845 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001846
Chris Lattner0a8191e2010-01-05 07:50:36 +00001847 if (ShouldSwap) {
1848 std::swap(LHS, RHS);
1849 std::swap(LHSCst, RHSCst);
1850 std::swap(LHSCC, RHSCC);
1851 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001852
Dan Gohman4a618822010-02-10 16:03:48 +00001853 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001854 // comparing a value against two constants and or'ing the result
1855 // together. Because of the above check, we know that we only have
1856 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1857 // icmp folding check above), that the two constants are not
1858 // equal.
1859 assert(LHSCst != RHSCst && "Compares not folded above?");
1860
1861 switch (LHSCC) {
1862 default: llvm_unreachable("Unknown integer condition code!");
1863 case ICmpInst::ICMP_EQ:
1864 switch (RHSCC) {
1865 default: llvm_unreachable("Unknown integer condition code!");
1866 case ICmpInst::ICMP_EQ:
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001867 if (LHS->getOperand(0) == RHS->getOperand(0)) {
Jakub Staszakf5849772012-12-31 01:40:44 +00001868 // if LHSCst and RHSCst differ only by one bit:
David Majnemer942003a2015-12-02 16:15:07 +00001869 // (A == C1 || A == C2) -> (A | (C1 ^ C2)) == C2
Jakub Staszakc48bbe72012-12-31 18:26:42 +00001870 assert(LHSCst->getValue().ule(LHSCst->getValue()));
1871
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001872 APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1873 if (Xor.isPowerOf2()) {
David Majnemer942003a2015-12-02 16:15:07 +00001874 Value *Cst = Builder->getInt(Xor);
1875 Value *Or = Builder->CreateOr(LHS->getOperand(0), Cst);
1876 return Builder->CreateICmp(ICmpInst::ICMP_EQ, Or, RHSCst);
Jakub Staszakea2b9b92012-12-31 00:34:55 +00001877 }
1878 }
1879
David Majnemer1fae1952013-04-14 21:15:43 +00001880 if (LHSCst == SubOne(RHSCst)) {
1881 // (X == 13 | X == 14) -> X-13 <u 2
1882 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1883 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1884 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1885 return Builder->CreateICmpULT(Add, AddCST);
1886 }
1887
Chris Lattner0a8191e2010-01-05 07:50:36 +00001888 break; // (X == 13 | X == 15) -> no change
1889 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1890 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1891 break;
1892 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1893 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1894 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001895 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001896 }
1897 break;
1898 case ICmpInst::ICMP_NE:
1899 switch (RHSCC) {
1900 default: llvm_unreachable("Unknown integer condition code!");
1901 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1902 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1903 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattner067459c2010-03-05 08:46:26 +00001904 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001905 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1906 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1907 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001908 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001909 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001910 case ICmpInst::ICMP_ULT:
1911 switch (RHSCC) {
1912 default: llvm_unreachable("Unknown integer condition code!");
1913 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1914 break;
1915 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1916 // If RHSCst is [us]MAXINT, it is always false. Not handling
1917 // this can cause overflow.
1918 if (RHSCst->isMaxValue(false))
Chris Lattner067459c2010-03-05 08:46:26 +00001919 return LHS;
Sanjay Patel85d79742016-08-31 19:49:56 +00001920 return insertRangeTest(Val, LHSCst->getValue(), RHSCst->getValue() + 1,
1921 false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001922 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1923 break;
1924 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1925 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001926 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001927 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1928 break;
1929 }
1930 break;
1931 case ICmpInst::ICMP_SLT:
1932 switch (RHSCC) {
1933 default: llvm_unreachable("Unknown integer condition code!");
1934 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1935 break;
1936 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1937 // If RHSCst is [us]MAXINT, it is always false. Not handling
1938 // this can cause overflow.
1939 if (RHSCst->isMaxValue(true))
Chris Lattner067459c2010-03-05 08:46:26 +00001940 return LHS;
Sanjay Patel85d79742016-08-31 19:49:56 +00001941 return insertRangeTest(Val, LHSCst->getValue(), RHSCst->getValue() + 1,
1942 true, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001943 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1944 break;
1945 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1946 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
Chris Lattner067459c2010-03-05 08:46:26 +00001947 return RHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001948 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1949 break;
1950 }
1951 break;
1952 case ICmpInst::ICMP_UGT:
1953 switch (RHSCC) {
1954 default: llvm_unreachable("Unknown integer condition code!");
1955 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1956 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
Chris Lattner067459c2010-03-05 08:46:26 +00001957 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001958 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1959 break;
1960 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1961 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001962 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001963 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1964 break;
1965 }
1966 break;
1967 case ICmpInst::ICMP_SGT:
1968 switch (RHSCC) {
1969 default: llvm_unreachable("Unknown integer condition code!");
1970 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1971 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
Chris Lattner067459c2010-03-05 08:46:26 +00001972 return LHS;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001973 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1974 break;
1975 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1976 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Jakub Staszak461d1fe2013-06-06 00:37:23 +00001977 return Builder->getTrue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001978 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1979 break;
1980 }
1981 break;
1982 }
Craig Topperf40110f2014-04-25 05:29:35 +00001983 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001984}
1985
Sanjay Patel18549272015-09-08 18:24:36 +00001986/// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
1987/// a Value which should already be inserted into the function.
Chris Lattner067459c2010-03-05 08:46:26 +00001988Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +00001989 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1990 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1991 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1992
1993 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1994 // Swap RHS operands to match LHS.
1995 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1996 std::swap(Op1LHS, Op1RHS);
1997 }
1998
1999 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
2000 // This is a similar transformation to the one in FoldAndOfFCmps.
2001 //
2002 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
2003 // bool(R & CC0) || bool(R & CC1)
2004 // = bool((R & CC0) | (R & CC1))
2005 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
2006 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
2007 return getFCmpValue(getFCmpCode(Op0CC) | getFCmpCode(Op1CC), Op0LHS, Op0RHS,
2008 Builder);
2009
Chris Lattner0a8191e2010-01-05 07:50:36 +00002010 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Craig Topper9d4171a2012-12-20 07:09:41 +00002011 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002012 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
2013 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
2014 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
2015 // If either of the constants are nans, then the whole thing returns
2016 // true.
2017 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002018 return Builder->getTrue();
Craig Topper9d4171a2012-12-20 07:09:41 +00002019
Chris Lattner0a8191e2010-01-05 07:50:36 +00002020 // Otherwise, no need to compare the two constants, compare the
2021 // rest.
Chris Lattner067459c2010-03-05 08:46:26 +00002022 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002023 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002024
Chris Lattner0a8191e2010-01-05 07:50:36 +00002025 // Handle vector zeros. This occurs because the canonical form of
2026 // "fcmp uno x,x" is "fcmp uno x, 0".
2027 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
2028 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002029 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Craig Topper9d4171a2012-12-20 07:09:41 +00002030
Craig Topperf40110f2014-04-25 05:29:35 +00002031 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002032 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002033
Craig Topperf40110f2014-04-25 05:29:35 +00002034 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002035}
2036
Sanjay Patel18549272015-09-08 18:24:36 +00002037/// This helper function folds:
Chris Lattner0a8191e2010-01-05 07:50:36 +00002038///
2039/// ((A | B) & C1) | (B & C2)
2040///
2041/// into:
Craig Topper9d4171a2012-12-20 07:09:41 +00002042///
Chris Lattner0a8191e2010-01-05 07:50:36 +00002043/// (A & C1) | B
2044///
2045/// when the XOR of the two constants is "all ones" (-1).
2046Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
2047 Value *A, Value *B, Value *C) {
2048 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
Craig Topperf40110f2014-04-25 05:29:35 +00002049 if (!CI1) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002050
Craig Topperf40110f2014-04-25 05:29:35 +00002051 Value *V1 = nullptr;
2052 ConstantInt *CI2 = nullptr;
2053 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002054
2055 APInt Xor = CI1->getValue() ^ CI2->getValue();
Craig Topperf40110f2014-04-25 05:29:35 +00002056 if (!Xor.isAllOnesValue()) return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002057
2058 if (V1 == A || V1 == B) {
2059 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
2060 return BinaryOperator::CreateOr(NewOp, V1);
2061 }
2062
Craig Topperf40110f2014-04-25 05:29:35 +00002063 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002064}
2065
David Majnemer5d1aeba2014-08-21 05:14:48 +00002066/// \brief This helper function folds:
2067///
2068/// ((A | B) & C1) ^ (B & C2)
2069///
2070/// into:
2071///
2072/// (A & C1) ^ B
2073///
2074/// when the XOR of the two constants is "all ones" (-1).
2075Instruction *InstCombiner::FoldXorWithConstants(BinaryOperator &I, Value *Op,
2076 Value *A, Value *B, Value *C) {
2077 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2078 if (!CI1)
2079 return nullptr;
2080
2081 Value *V1 = nullptr;
2082 ConstantInt *CI2 = nullptr;
2083 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
2084 return nullptr;
2085
2086 APInt Xor = CI1->getValue() ^ CI2->getValue();
2087 if (!Xor.isAllOnesValue())
2088 return nullptr;
2089
2090 if (V1 == A || V1 == B) {
2091 Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
2092 return BinaryOperator::CreateXor(NewOp, V1);
2093 }
2094
2095 return nullptr;
2096}
2097
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002098// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2099// here. We should standardize that construct where it is needed or choose some
2100// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002101Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002102 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002103 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2104
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002105 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002106 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002107
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002108 if (Value *V = SimplifyOrInst(Op0, Op1, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00002109 return replaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00002110
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002111 // (A&B)|(A&C) -> A&(B|C) etc
2112 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002113 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002114
Craig Topper9d4171a2012-12-20 07:09:41 +00002115 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002116 // purpose is to compute bits we don't care about.
2117 if (SimplifyDemandedInstructionBits(I))
2118 return &I;
2119
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002120 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002121 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002122
Chris Lattner0a8191e2010-01-05 07:50:36 +00002123 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Craig Topperf40110f2014-04-25 05:29:35 +00002124 ConstantInt *C1 = nullptr; Value *X = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002125 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2126 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
2127 Op0->hasOneUse()) {
2128 Value *Or = Builder->CreateOr(X, RHS);
2129 Or->takeName(Op0);
2130 return BinaryOperator::CreateXor(Or,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002131 Builder->getInt(C1->getValue() & ~RHS->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002132 }
2133
Sanjay Pateldb0938f2017-01-10 23:49:07 +00002134 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2135 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002136 }
2137
Chad Rosiere5819e22016-05-26 14:58:51 +00002138 // Given an OR instruction, check to see if this is a bswap.
2139 if (Instruction *BSwap = MatchBSwap(I))
2140 return BSwap;
2141
Craig Topperf40110f2014-04-25 05:29:35 +00002142 Value *A = nullptr, *B = nullptr;
2143 ConstantInt *C1 = nullptr, *C2 = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002144
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002145 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002146 if (Op0->hasOneUse() &&
2147 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002148 MaskedValueIsZero(Op1, C1->getValue(), 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002149 Value *NOr = Builder->CreateOr(A, Op1);
2150 NOr->takeName(Op0);
2151 return BinaryOperator::CreateXor(NOr, C1);
2152 }
2153
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002154 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002155 if (Op1->hasOneUse() &&
2156 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002157 MaskedValueIsZero(Op0, C1->getValue(), 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002158 Value *NOr = Builder->CreateOr(A, Op0);
2159 NOr->takeName(Op0);
2160 return BinaryOperator::CreateXor(NOr, C1);
2161 }
2162
Suyog Sardad64faf62014-07-22 18:09:41 +00002163 // ((~A & B) | A) -> (A | B)
2164 if (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2165 match(Op1, m_Specific(A)))
2166 return BinaryOperator::CreateOr(A, B);
2167
2168 // ((A & B) | ~A) -> (~A | B)
2169 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2170 match(Op1, m_Not(m_Specific(A))))
2171 return BinaryOperator::CreateOr(Builder->CreateNot(A), B);
2172
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002173 // (A & ~B) | (A ^ B) -> (A ^ B)
2174 // (~B & A) | (A ^ B) -> (A ^ B)
2175 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
Suyog Sarda52324c82014-08-01 04:50:31 +00002176 match(Op1, m_Xor(m_Specific(A), m_Specific(B))))
2177 return BinaryOperator::CreateXor(A, B);
2178
Sanjay Patel5a443ac2016-12-19 18:35:37 +00002179 // Commute the 'or' operands.
2180 // (A ^ B) | (A & ~B) -> (A ^ B)
2181 // (A ^ B) | (~B & A) -> (A ^ B)
2182 if (match(Op1, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
2183 match(Op0, m_Xor(m_Specific(A), m_Specific(B))))
Suyog Sarda52324c82014-08-01 04:50:31 +00002184 return BinaryOperator::CreateXor(A, B);
2185
Chris Lattner0a8191e2010-01-05 07:50:36 +00002186 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00002187 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002188 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2189 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperf40110f2014-04-25 05:29:35 +00002190 Value *V1 = nullptr, *V2 = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002191 C1 = dyn_cast<ConstantInt>(C);
2192 C2 = dyn_cast<ConstantInt>(D);
2193 if (C1 && C2) { // (A & C1)|(B & C2)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002194 if ((C1->getValue() & C2->getValue()) == 0) {
Chris Lattner95188692010-01-11 06:55:24 +00002195 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002196 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002197 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002198 ((V1 == B &&
2199 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2200 (V2 == B &&
2201 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002202 return BinaryOperator::CreateAnd(A,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002203 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002204 // Or commutes, try both ways.
2205 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002206 ((V1 == A &&
2207 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2208 (V2 == A &&
2209 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002210 return BinaryOperator::CreateAnd(B,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002211 Builder->getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002212
Chris Lattner95188692010-01-11 06:55:24 +00002213 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002214 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00002215 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00002216 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2217 (C3->getValue() & ~C1->getValue()) == 0 &&
2218 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2219 (C4->getValue() & ~C2->getValue()) == 0) {
2220 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2221 return BinaryOperator::CreateAnd(V2,
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002222 Builder->getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002223 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002224 }
2225 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002226
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002227 // Don't try to form a select if it's unlikely that we'll get rid of at
2228 // least one of the operands. A select is generally more expensive than the
2229 // 'or' that it is replacing.
2230 if (Op0->hasOneUse() || Op1->hasOneUse()) {
2231 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
2232 if (Value *V = matchSelectFromAndOr(A, C, B, D, *Builder))
2233 return replaceInstUsesWith(I, V);
2234 if (Value *V = matchSelectFromAndOr(A, C, D, B, *Builder))
2235 return replaceInstUsesWith(I, V);
2236 if (Value *V = matchSelectFromAndOr(C, A, B, D, *Builder))
2237 return replaceInstUsesWith(I, V);
2238 if (Value *V = matchSelectFromAndOr(C, A, D, B, *Builder))
2239 return replaceInstUsesWith(I, V);
2240 if (Value *V = matchSelectFromAndOr(B, D, A, C, *Builder))
2241 return replaceInstUsesWith(I, V);
2242 if (Value *V = matchSelectFromAndOr(B, D, C, A, *Builder))
2243 return replaceInstUsesWith(I, V);
2244 if (Value *V = matchSelectFromAndOr(D, B, A, C, *Builder))
2245 return replaceInstUsesWith(I, V);
2246 if (Value *V = matchSelectFromAndOr(D, B, C, A, *Builder))
2247 return replaceInstUsesWith(I, V);
2248 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002249
2250 // ((A&~B)|(~A&B)) -> A^B
2251 if ((match(C, m_Not(m_Specific(D))) &&
2252 match(B, m_Not(m_Specific(A)))))
2253 return BinaryOperator::CreateXor(A, D);
2254 // ((~B&A)|(~A&B)) -> A^B
2255 if ((match(A, m_Not(m_Specific(D))) &&
2256 match(B, m_Not(m_Specific(C)))))
2257 return BinaryOperator::CreateXor(C, D);
2258 // ((A&~B)|(B&~A)) -> A^B
2259 if ((match(C, m_Not(m_Specific(B))) &&
2260 match(D, m_Not(m_Specific(A)))))
2261 return BinaryOperator::CreateXor(A, B);
2262 // ((~B&A)|(B&~A)) -> A^B
2263 if ((match(A, m_Not(m_Specific(B))) &&
2264 match(D, m_Not(m_Specific(C)))))
2265 return BinaryOperator::CreateXor(C, B);
Benjamin Kramer11743242010-07-12 13:34:22 +00002266
2267 // ((A|B)&1)|(B&-2) -> (A&1) | B
2268 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2269 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2270 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2271 if (Ret) return Ret;
2272 }
2273 // (B&-2)|((A|B)&1) -> (A&1) | B
2274 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2275 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2276 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2277 if (Ret) return Ret;
2278 }
David Majnemer5d1aeba2014-08-21 05:14:48 +00002279 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
2280 if (match(A, m_Xor(m_Value(V1), m_Specific(B))) ||
2281 match(A, m_Xor(m_Specific(B), m_Value(V1)))) {
2282 Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C);
2283 if (Ret) return Ret;
2284 }
2285 // (B&-2)|((A^B)&1) -> (A&1) ^ B
2286 if (match(B, m_Xor(m_Specific(A), m_Value(V1))) ||
2287 match(B, m_Xor(m_Value(V1), m_Specific(A)))) {
2288 Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D);
2289 if (Ret) return Ret;
2290 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002291 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002292
David Majnemer42af3602014-07-30 21:26:37 +00002293 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2294 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2295 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2296 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
2297 return BinaryOperator::CreateOr(Op0, C);
2298
2299 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2300 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2301 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2302 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
2303 return BinaryOperator::CreateOr(Op1, C);
2304
David Majnemerf1eda232014-08-14 06:41:38 +00002305 // ((B | C) & A) | B -> B | (A & C)
2306 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2307 return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2308
Sanjay Patelb54e62f2015-09-08 20:14:13 +00002309 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
2310 return DeMorgan;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002311
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002312 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002313 bool SwappedForXor = false;
2314 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002315 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002316 SwappedForXor = true;
2317 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002318
2319 // A | ( A ^ B) -> A | B
2320 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002321 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002322 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2323 if (Op0 == A || Op0 == B)
2324 return BinaryOperator::CreateOr(A, B);
2325
Chad Rosier7813dce2012-04-26 23:29:14 +00002326 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2327 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2328 return BinaryOperator::CreateOr(A, B);
2329
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002330 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2331 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2332 return BinaryOperator::CreateOr(Not, Op0);
2333 }
2334 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2335 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2336 return BinaryOperator::CreateOr(Not, Op0);
2337 }
2338 }
2339
2340 // A | ~(A | B) -> A | ~B
2341 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002342 if (match(Op1, m_Not(m_Value(A))))
2343 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002344 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2345 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2346 B->getOpcode() == Instruction::Xor)) {
2347 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2348 B->getOperand(0);
2349 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2350 return BinaryOperator::CreateOr(Not, Op0);
2351 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002352
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002353 // (A & B) | (~A ^ B) -> (~A ^ B)
2354 // (A & B) | (B ^ ~A) -> (~A ^ B)
2355 // (B & A) | (~A ^ B) -> (~A ^ B)
2356 // (B & A) | (B ^ ~A) -> (~A ^ B)
2357 // The match order is important: match the xor first because the 'not'
2358 // operation defines 'A'. We do not need to match the xor as Op0 because the
2359 // xor was canonicalized to Op1 above.
2360 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2361 match(Op0, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sarda16d64652014-08-01 04:41:43 +00002362 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2363
Eli Friedmane06535b2012-03-16 00:52:42 +00002364 if (SwappedForXor)
2365 std::swap(Op0, Op1);
2366
David Majnemer3d6f80b2014-11-28 19:58:29 +00002367 {
2368 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2369 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2370 if (LHS && RHS)
Hal Finkel60db0582014-09-07 18:57:58 +00002371 if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002372 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002373
David Majnemer3d6f80b2014-11-28 19:58:29 +00002374 // TODO: Make this recursive; it's a little tricky because an arbitrary
2375 // number of 'or' instructions might have to be created.
2376 Value *X, *Y;
2377 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2378 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2379 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002380 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002381 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2382 if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002383 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002384 }
2385 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2386 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2387 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002388 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002389 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2390 if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002391 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002392 }
2393 }
2394
Chris Lattner4e8137d2010-02-11 06:26:33 +00002395 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2396 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2397 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Chris Lattner067459c2010-03-05 08:46:26 +00002398 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00002399 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002400
Sanjay Patel75b4ae22016-02-23 23:56:23 +00002401 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2402 return CastedOr;
Eli Friedman23956262011-04-14 22:41:27 +00002403
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002404 // 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 +00002405 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002406 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002407 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
Sanjay Patel1b6b8242016-07-08 17:26:47 +00002408 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002409 A->getType()->getScalarType()->isIntegerTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002410 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2411
Owen Andersonc237a842010-09-13 17:59:27 +00002412 // Note: If we've gotten to the point of visiting the outer OR, then the
2413 // inner one couldn't be simplified. If it was a constant, then it won't
2414 // be simplified by a later pass either, so we try swapping the inner/outer
2415 // ORs in the hopes that we'll be able to simplify it this way.
2416 // (X|C) | V --> (X|V) | C
2417 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2418 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2419 Value *Inner = Builder->CreateOr(A, Op1);
2420 Inner->takeName(Op0);
2421 return BinaryOperator::CreateOr(Inner, C1);
2422 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002423
Bill Wendling23242092013-02-16 23:41:36 +00002424 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2425 // Since this OR statement hasn't been optimized further yet, we hope
2426 // that this transformation will allow the new ORs to be optimized.
2427 {
Craig Topperf40110f2014-04-25 05:29:35 +00002428 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002429 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2430 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2431 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2432 Value *orTrue = Builder->CreateOr(A, C);
2433 Value *orFalse = Builder->CreateOr(B, D);
2434 return SelectInst::Create(X, orTrue, orFalse);
2435 }
2436 }
2437
Craig Topperf40110f2014-04-25 05:29:35 +00002438 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002439}
2440
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002441// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2442// here. We should standardize that construct where it is needed or choose some
2443// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002444Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002445 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002446 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2447
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002448 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002449 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002450
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002451 if (Value *V = SimplifyXorInst(Op0, Op1, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00002452 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002453
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002454 // (A&B)^(A&C) -> A&(B^C) etc
2455 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002456 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002457
Craig Topper9d4171a2012-12-20 07:09:41 +00002458 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002459 // purpose is to compute bits we don't care about.
2460 if (SimplifyDemandedInstructionBits(I))
2461 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002462
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002463 if (Value *V = SimplifyBSwap(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002464 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002465
Chris Lattner0a8191e2010-01-05 07:50:36 +00002466 // Is this a ~ operation?
2467 if (Value *NotOp = dyn_castNotVal(&I)) {
2468 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002469 if (Op0I->getOpcode() == Instruction::And ||
Chris Lattner0a8191e2010-01-05 07:50:36 +00002470 Op0I->getOpcode() == Instruction::Or) {
2471 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2472 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2473 if (dyn_castNotVal(Op0I->getOperand(1)))
2474 Op0I->swapOperands();
2475 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2476 Value *NotY =
2477 Builder->CreateNot(Op0I->getOperand(1),
2478 Op0I->getOperand(1)->getName()+".not");
2479 if (Op0I->getOpcode() == Instruction::And)
2480 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2481 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2482 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002483
Chris Lattner0a8191e2010-01-05 07:50:36 +00002484 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2485 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
Sanjoy Das82ea3d42015-02-24 00:08:41 +00002486 if (IsFreeToInvert(Op0I->getOperand(0),
2487 Op0I->getOperand(0)->hasOneUse()) &&
2488 IsFreeToInvert(Op0I->getOperand(1),
2489 Op0I->getOperand(1)->hasOneUse())) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002490 Value *NotX =
2491 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2492 Value *NotY =
2493 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2494 if (Op0I->getOpcode() == Instruction::And)
2495 return BinaryOperator::CreateOr(NotX, NotY);
2496 return BinaryOperator::CreateAnd(NotX, NotY);
2497 }
Chris Lattner18f49ce2010-01-19 18:16:19 +00002498
2499 } else if (Op0I->getOpcode() == Instruction::AShr) {
2500 // ~(~X >>s Y) --> (X >>s Y)
2501 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2502 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002503 }
2504 }
2505 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002506
Benjamin Kramer443c7962015-02-12 20:26:46 +00002507 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
2508 if (RHS->isAllOnesValue() && Op0->hasOneUse())
Chris Lattner0a8191e2010-01-05 07:50:36 +00002509 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Dan Gohman0a8175d2010-04-09 14:53:59 +00002510 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2511 return CmpInst::Create(CI->getOpcode(),
2512 CI->getInversePredicate(),
2513 CI->getOperand(0), CI->getOperand(1));
Benjamin Kramer443c7962015-02-12 20:26:46 +00002514 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002515
Benjamin Kramer443c7962015-02-12 20:26:46 +00002516 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002517 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2518 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2519 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2520 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2521 Instruction::CastOps Opcode = Op0C->getOpcode();
2522 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002523 (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
Chris Lattner0a8191e2010-01-05 07:50:36 +00002524 Op0C->getDestTy()))) {
2525 CI->setPredicate(CI->getInversePredicate());
2526 return CastInst::Create(Opcode, CI, Op0C->getType());
2527 }
2528 }
2529 }
2530 }
2531
2532 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2533 // ~(c-X) == X-c-1 == X+(-c-1)
2534 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2535 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2536 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2537 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2538 ConstantInt::get(I.getType(), 1));
2539 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2540 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002541
Chris Lattner0a8191e2010-01-05 07:50:36 +00002542 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2543 if (Op0I->getOpcode() == Instruction::Add) {
2544 // ~(X-c) --> (-c-1)-X
2545 if (RHS->isAllOnesValue()) {
2546 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2547 return BinaryOperator::CreateSub(
2548 ConstantExpr::getSub(NegOp0CI,
2549 ConstantInt::get(I.getType(), 1)),
2550 Op0I->getOperand(0));
2551 } else if (RHS->getValue().isSignBit()) {
2552 // (X + C) ^ signbit -> (X + C + signbit)
Jakub Staszak461d1fe2013-06-06 00:37:23 +00002553 Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
Chris Lattner0a8191e2010-01-05 07:50:36 +00002554 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2555
2556 }
2557 } else if (Op0I->getOpcode() == Instruction::Or) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002558 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Hal Finkel60db0582014-09-07 18:57:58 +00002559 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2560 0, &I)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002561 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2562 // Anything in both C1 and C2 is known to be zero, remove it from
2563 // NewRHS.
2564 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
Craig Topper9d4171a2012-12-20 07:09:41 +00002565 NewRHS = ConstantExpr::getAnd(NewRHS,
Chris Lattner0a8191e2010-01-05 07:50:36 +00002566 ConstantExpr::getNot(CommonBits));
2567 Worklist.Add(Op0I);
2568 I.setOperand(0, Op0I->getOperand(0));
2569 I.setOperand(1, NewRHS);
2570 return &I;
2571 }
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002572 } else if (Op0I->getOpcode() == Instruction::LShr) {
2573 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2574 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002575 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002576 ConstantInt *C1;
2577 if (Op0I->hasOneUse() &&
2578 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2579 E1->getOpcode() == Instruction::Xor &&
2580 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2581 // fold (C1 >> C2) ^ C3
2582 ConstantInt *C2 = Op0CI, *C3 = RHS;
2583 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2584 FoldConst ^= C3->getValue();
2585 // Prepare the two operands.
2586 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2587 Opnd0->takeName(Op0I);
2588 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2589 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2590
2591 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2592 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002593 }
2594 }
2595 }
2596
Sanjay Pateldb0938f2017-01-10 23:49:07 +00002597 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2598 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002599 }
2600
Chris Lattner0a8191e2010-01-05 07:50:36 +00002601 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2602 if (Op1I) {
2603 Value *A, *B;
2604 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2605 if (A == Op0) { // B^(B|A) == (A|B)^B
2606 Op1I->swapOperands();
2607 I.swapOperands();
2608 std::swap(Op0, Op1);
2609 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2610 I.swapOperands(); // Simplified below.
2611 std::swap(Op0, Op1);
2612 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002613 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002614 Op1I->hasOneUse()){
2615 if (A == Op0) { // A^(A&B) -> A^(B&A)
2616 Op1I->swapOperands();
2617 std::swap(A, B);
2618 }
2619 if (B == Op0) { // A^(B&A) -> (B&A)^A
2620 I.swapOperands(); // Simplified below.
2621 std::swap(Op0, Op1);
2622 }
2623 }
2624 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002625
Chris Lattner0a8191e2010-01-05 07:50:36 +00002626 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2627 if (Op0I) {
2628 Value *A, *B;
2629 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2630 Op0I->hasOneUse()) {
2631 if (A == Op1) // (B|A)^B == (A|B)^B
2632 std::swap(A, B);
2633 if (B == Op1) // (A|B)^B == A & ~B
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002634 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
Craig Topper9d4171a2012-12-20 07:09:41 +00002635 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +00002636 Op0I->hasOneUse()){
2637 if (A == Op1) // (A&B)^A -> (B&A)^A
2638 std::swap(A, B);
2639 if (B == Op1 && // (B&A)^A == ~B & A
2640 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002641 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002642 }
2643 }
2644 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002645
Chris Lattner0a8191e2010-01-05 07:50:36 +00002646 if (Op0I && Op1I) {
2647 Value *A, *B, *C, *D;
2648 // (A & B)^(A | B) -> A ^ B
2649 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2650 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002651 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002652 return BinaryOperator::CreateXor(A, B);
2653 }
2654 // (A | B)^(A & B) -> A ^ B
2655 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2656 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Craig Topper9d4171a2012-12-20 07:09:41 +00002657 if ((A == C && B == D) || (A == D && B == C))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002658 return BinaryOperator::CreateXor(A, B);
2659 }
David Majnemer698dca02014-08-14 06:46:25 +00002660 // (A | ~B) ^ (~A | B) -> A ^ B
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002661 // (~B | A) ^ (~A | B) -> A ^ B
2662 if (match(Op0I, m_c_Or(m_Value(A), m_Not(m_Value(B)))) &&
2663 match(Op1I, m_Or(m_Not(m_Specific(A)), m_Specific(B))))
David Majnemer698dca02014-08-14 06:46:25 +00002664 return BinaryOperator::CreateXor(A, B);
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002665
David Majnemer698dca02014-08-14 06:46:25 +00002666 // (~A | B) ^ (A | ~B) -> A ^ B
2667 if (match(Op0I, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2668 match(Op1I, m_Or(m_Specific(A), m_Not(m_Specific(B))))) {
2669 return BinaryOperator::CreateXor(A, B);
2670 }
Mayur Pandey960507b2014-08-19 08:19:19 +00002671 // (A & ~B) ^ (~A & B) -> A ^ B
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002672 // (~B & A) ^ (~A & B) -> A ^ B
2673 if (match(Op0I, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
2674 match(Op1I, m_And(m_Not(m_Specific(A)), m_Specific(B))))
Mayur Pandey960507b2014-08-19 08:19:19 +00002675 return BinaryOperator::CreateXor(A, B);
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002676
Mayur Pandey960507b2014-08-19 08:19:19 +00002677 // (~A & B) ^ (A & ~B) -> A ^ B
2678 if (match(Op0I, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2679 match(Op1I, m_And(m_Specific(A), m_Not(m_Specific(B))))) {
2680 return BinaryOperator::CreateXor(A, B);
2681 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002682 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
2683 if (match(Op0I, m_Xor(m_Value(D), m_Value(C))) &&
2684 match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2685 if (D == A)
2686 return BinaryOperator::CreateXor(
2687 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2688 if (D == B)
2689 return BinaryOperator::CreateXor(
2690 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002691 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002692 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Karthik Bhata4a4db92014-08-13 05:13:14 +00002693 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
David Majnemer6fe6ea72014-09-05 06:09:24 +00002694 match(Op1I, m_Xor(m_Value(D), m_Value(C)))) {
2695 if (D == A)
2696 return BinaryOperator::CreateXor(
2697 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2698 if (D == B)
2699 return BinaryOperator::CreateXor(
2700 Builder->CreateAnd(Builder->CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002701 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002702 // (A & B) ^ (A ^ B) -> (A | B)
2703 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2704 match(Op1I, m_Xor(m_Specific(A), m_Specific(B))))
2705 return BinaryOperator::CreateOr(A, B);
2706 // (A ^ B) ^ (A & B) -> (A | B)
2707 if (match(Op0I, m_Xor(m_Value(A), m_Value(B))) &&
2708 match(Op1I, m_And(m_Specific(A), m_Specific(B))))
2709 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002710 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002711
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002712 // (A & ~B) ^ ~A -> ~(A & B)
2713 // (~B & A) ^ ~A -> ~(A & B)
2714 Value *A, *B;
2715 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
Suyog Sarda56c9a872014-08-01 05:07:20 +00002716 match(Op1, m_Not(m_Specific(A))))
2717 return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2718
David Majnemerb0761a02016-12-21 19:21:59 +00002719 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002720 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
David Majnemerb0761a02016-12-21 19:21:59 +00002721 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
Chris Lattner0a8191e2010-01-05 07:50:36 +00002722 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2723 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2724 LHS->getOperand(1) == RHS->getOperand(0))
2725 LHS->swapOperands();
2726 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2727 LHS->getOperand(1) == RHS->getOperand(1)) {
2728 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2729 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2730 bool isSigned = LHS->isSigned() || RHS->isSigned();
Sanjay Patel4b198802016-02-01 22:23:39 +00002731 return replaceInstUsesWith(I,
Pete Cooperebf98c12011-12-17 01:20:32 +00002732 getNewICmpValue(isSigned, Code, Op0, Op1,
2733 Builder));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002734 }
2735 }
2736
Sanjay Pateldbbaca02016-02-24 17:00:34 +00002737 if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2738 return CastedXor;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002739
Craig Topperf40110f2014-04-25 05:29:35 +00002740 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002741}